Added information on function name added to LogRecord, and the 'extra' keyword parameter.
[python.git] / Modules / main.c
blobf6fa48bdd6dee17c369d8e2ead3c39385adb4fc2
1 /* Python interpreter main program */
3 #include "Python.h"
4 #include "osdefs.h"
5 #include "code.h" /* For CO_FUTURE_DIVISION */
6 #include "import.h"
8 #ifdef __VMS
9 #include <unixlib.h>
10 #endif
12 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
13 #include <fcntl.h>
14 #endif
16 #if (defined(PYOS_OS2) && !defined(PYCC_GCC)) || defined(MS_WINDOWS)
17 #define PYTHONHOMEHELP "<prefix>\\lib"
18 #else
19 #if defined(PYOS_OS2) && defined(PYCC_GCC)
20 #define PYTHONHOMEHELP "<prefix>/Lib"
21 #else
22 #define PYTHONHOMEHELP "<prefix>/pythonX.X"
23 #endif
24 #endif
26 #include "pygetopt.h"
28 #define COPYRIGHT \
29 "Type \"help\", \"copyright\", \"credits\" or \"license\" " \
30 "for more information."
32 /* For Py_GetArgcArgv(); set by main() */
33 static char **orig_argv;
34 static int orig_argc;
36 /* command line options */
37 #define BASE_OPTS "c:dEhim:OQ:StuUvVW:xX"
39 #ifndef RISCOS
40 #define PROGRAM_OPTS BASE_OPTS
41 #else /*RISCOS*/
42 /* extra option saying that we are running under a special task window
43 frontend; especially my_readline will behave different */
44 #define PROGRAM_OPTS BASE_OPTS "w"
45 /* corresponding flag */
46 extern int Py_RISCOSWimpFlag;
47 #endif /*RISCOS*/
49 /* Short usage message (with %s for argv0) */
50 static char *usage_line =
51 "usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
53 /* Long usage message, split into parts < 512 bytes */
54 static char *usage_1 = "\
55 Options and arguments (and corresponding environment variables):\n\
56 -c cmd : program passed in as string (terminates option list)\n\
57 -d : debug output from parser (also PYTHONDEBUG=x)\n\
58 -E : ignore environment variables (such as PYTHONPATH)\n\
59 -h : print this help message and exit\n\
60 -i : inspect interactively after running script, (also PYTHONINSPECT=x)\n\
61 and force prompts, even if stdin does not appear to be a terminal\n\
63 static char *usage_2 = "\
64 -m mod : run library module as a script (terminates option list)\n\
65 -O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)\n\
66 -OO : remove doc-strings in addition to the -O optimizations\n\
67 -Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew\n\
68 -S : don't imply 'import site' on initialization\n\
69 -t : issue warnings about inconsistent tab usage (-tt: issue errors)\n\
70 -u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x)\n\
72 static char *usage_3 = "\
73 see man page for details on internal buffering relating to '-u'\n\
74 -v : verbose (trace import statements) (also PYTHONVERBOSE=x)\n\
75 -V : print the Python version number and exit\n\
76 -W arg : warning control (arg is action:message:category:module:lineno)\n\
77 -x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
78 file : program read from script file\n\
79 - : program read from stdin (default; interactive mode if a tty)\n\
81 static char *usage_4 = "\
82 arg ...: arguments passed to program in sys.argv[1:]\n\
83 Other environment variables:\n\
84 PYTHONSTARTUP: file executed on interactive startup (no default)\n\
85 PYTHONPATH : '%c'-separated list of directories prefixed to the\n\
86 default module search path. The result is sys.path.\n\
87 PYTHONHOME : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
88 The default module search path uses %s.\n\
89 PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
93 static int
94 usage(int exitcode, char* program)
96 FILE *f = exitcode ? stderr : stdout;
98 fprintf(f, usage_line, program);
99 if (exitcode)
100 fprintf(f, "Try `python -h' for more information.\n");
101 else {
102 fprintf(f, usage_1);
103 fprintf(f, usage_2);
104 fprintf(f, usage_3);
105 fprintf(f, usage_4, DELIM, DELIM, PYTHONHOMEHELP);
107 #if defined(__VMS)
108 if (exitcode == 0) {
109 /* suppress 'error' message */
110 return 1;
112 else {
113 /* STS$M_INHIB_MSG + SS$_ABORT */
114 return 0x1000002c;
116 #else
117 return exitcode;
118 #endif
119 /*NOTREACHED*/
122 static void RunStartupFile(PyCompilerFlags *cf)
124 char *startup = Py_GETENV("PYTHONSTARTUP");
125 if (startup != NULL && startup[0] != '\0') {
126 FILE *fp = fopen(startup, "r");
127 if (fp != NULL) {
128 (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
129 PyErr_Clear();
130 fclose(fp);
135 /* Get the path to a top-level module */
136 static struct filedescr * FindModule(const char *module,
137 FILE **fp, char **filename)
139 struct filedescr *fdescr = NULL;
140 *fp = NULL;
141 *filename = malloc(MAXPATHLEN);
143 if (*filename == NULL)
144 return NULL;
146 /* Find the actual module source code */
147 fdescr = _PyImport_FindModule(module, NULL,
148 *filename, MAXPATHLEN, fp, NULL);
150 if (fdescr == NULL) {
151 free(*filename);
152 *filename = NULL;
155 return fdescr;
158 /* Main program */
161 Py_Main(int argc, char **argv)
163 int c;
164 int sts;
165 char *command = NULL;
166 char *filename = NULL;
167 char *module = NULL;
168 FILE *fp = stdin;
169 char *p;
170 int inspect = 0;
171 int unbuffered = 0;
172 int skipfirstline = 0;
173 int stdin_is_interactive = 0;
174 int help = 0;
175 int version = 0;
176 int saw_inspect_flag = 0;
177 int saw_unbuffered_flag = 0;
178 PyCompilerFlags cf;
180 cf.cf_flags = 0;
182 orig_argc = argc; /* For Py_GetArgcArgv() */
183 orig_argv = argv;
185 #ifdef RISCOS
186 Py_RISCOSWimpFlag = 0;
187 #endif
189 PySys_ResetWarnOptions();
191 while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
192 if (c == 'c') {
193 /* -c is the last option; following arguments
194 that look like options are left for the
195 command to interpret. */
196 command = malloc(strlen(_PyOS_optarg) + 2);
197 if (command == NULL)
198 Py_FatalError(
199 "not enough memory to copy -c argument");
200 strcpy(command, _PyOS_optarg);
201 strcat(command, "\n");
202 break;
205 if (c == 'm') {
206 /* -m is the last option; following arguments
207 that look like options are left for the
208 module to interpret. */
209 module = malloc(strlen(_PyOS_optarg) + 2);
210 if (module == NULL)
211 Py_FatalError(
212 "not enough memory to copy -m argument");
213 strcpy(module, _PyOS_optarg);
214 break;
217 switch (c) {
219 case 'd':
220 Py_DebugFlag++;
221 break;
223 case 'Q':
224 if (strcmp(_PyOS_optarg, "old") == 0) {
225 Py_DivisionWarningFlag = 0;
226 break;
228 if (strcmp(_PyOS_optarg, "warn") == 0) {
229 Py_DivisionWarningFlag = 1;
230 break;
232 if (strcmp(_PyOS_optarg, "warnall") == 0) {
233 Py_DivisionWarningFlag = 2;
234 break;
236 if (strcmp(_PyOS_optarg, "new") == 0) {
237 /* This only affects __main__ */
238 cf.cf_flags |= CO_FUTURE_DIVISION;
239 /* And this tells the eval loop to treat
240 BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
241 _Py_QnewFlag = 1;
242 break;
244 fprintf(stderr,
245 "-Q option should be `-Qold', "
246 "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
247 return usage(2, argv[0]);
248 /* NOTREACHED */
250 case 'i':
251 inspect++;
252 saw_inspect_flag = 1;
253 Py_InteractiveFlag++;
254 break;
256 case 'O':
257 Py_OptimizeFlag++;
258 break;
260 case 'S':
261 Py_NoSiteFlag++;
262 break;
264 case 'E':
265 Py_IgnoreEnvironmentFlag++;
266 break;
268 case 't':
269 Py_TabcheckFlag++;
270 break;
272 case 'u':
273 unbuffered++;
274 saw_unbuffered_flag = 1;
275 break;
277 case 'v':
278 Py_VerboseFlag++;
279 break;
281 #ifdef RISCOS
282 case 'w':
283 Py_RISCOSWimpFlag = 1;
284 break;
285 #endif
287 case 'x':
288 skipfirstline = 1;
289 break;
291 case 'U':
292 Py_UnicodeFlag++;
293 break;
294 case 'h':
295 help++;
296 break;
297 case 'V':
298 version++;
299 break;
301 case 'W':
302 PySys_AddWarnOption(_PyOS_optarg);
303 break;
305 /* This space reserved for other options */
307 default:
308 return usage(2, argv[0]);
309 /*NOTREACHED*/
314 if (help)
315 return usage(0, argv[0]);
317 if (version) {
318 fprintf(stderr, "Python %s\n", PY_VERSION);
319 return 0;
322 if (!saw_inspect_flag &&
323 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
324 inspect = 1;
325 if (!saw_unbuffered_flag &&
326 (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
327 unbuffered = 1;
329 if (command == NULL && module == NULL && _PyOS_optind < argc &&
330 strcmp(argv[_PyOS_optind], "-") != 0)
332 #ifdef __VMS
333 filename = decc$translate_vms(argv[_PyOS_optind]);
334 if (filename == (char *)0 || filename == (char *)-1)
335 filename = argv[_PyOS_optind];
337 #else
338 filename = argv[_PyOS_optind];
339 #endif
340 if (filename != NULL) {
341 if ((fp = fopen(filename, "r")) == NULL) {
342 #ifdef HAVE_STRERROR
343 fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
344 argv[0], filename, errno, strerror(errno));
345 #else
346 fprintf(stderr, "%s: can't open file '%s': Errno %d\n",
347 argv[0], filename, errno);
348 #endif
349 return 2;
351 else if (skipfirstline) {
352 int ch;
353 /* Push back first newline so line numbers
354 remain the same */
355 while ((ch = getc(fp)) != EOF) {
356 if (ch == '\n') {
357 (void)ungetc(ch, fp);
358 break;
363 /* XXX: does this work on Win/Win64? (see posix_fstat) */
364 struct stat sb;
365 if (fstat(fileno(fp), &sb) == 0 &&
366 S_ISDIR(sb.st_mode)) {
367 fprintf(stderr, "%s: warning '%s' is a directory\n", argv[0], filename);
373 stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
375 if (unbuffered) {
376 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
377 _setmode(fileno(stdin), O_BINARY);
378 _setmode(fileno(stdout), O_BINARY);
379 #endif
380 #ifdef HAVE_SETVBUF
381 setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
382 setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
383 setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
384 #else /* !HAVE_SETVBUF */
385 setbuf(stdin, (char *)NULL);
386 setbuf(stdout, (char *)NULL);
387 setbuf(stderr, (char *)NULL);
388 #endif /* !HAVE_SETVBUF */
390 else if (Py_InteractiveFlag) {
391 #ifdef MS_WINDOWS
392 /* Doesn't have to have line-buffered -- use unbuffered */
393 /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
394 setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
395 #else /* !MS_WINDOWS */
396 #ifdef HAVE_SETVBUF
397 setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
398 setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
399 #endif /* HAVE_SETVBUF */
400 #endif /* !MS_WINDOWS */
401 /* Leave stderr alone - it should be unbuffered anyway. */
403 #ifdef __VMS
404 else {
405 setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
407 #endif /* __VMS */
409 #ifdef __APPLE__
410 /* On MacOS X, when the Python interpreter is embedded in an
411 application bundle, it gets executed by a bootstrapping script
412 that does os.execve() with an argv[0] that's different from the
413 actual Python executable. This is needed to keep the Finder happy,
414 or rather, to work around Apple's overly strict requirements of
415 the process name. However, we still need a usable sys.executable,
416 so the actual executable path is passed in an environment variable.
417 See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
418 script. */
419 if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')
420 Py_SetProgramName(p);
421 else
422 Py_SetProgramName(argv[0]);
423 #else
424 Py_SetProgramName(argv[0]);
425 #endif
426 Py_Initialize();
428 if (Py_VerboseFlag ||
429 (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
430 fprintf(stderr, "Python %s on %s\n",
431 Py_GetVersion(), Py_GetPlatform());
432 if (!Py_NoSiteFlag)
433 fprintf(stderr, "%s\n", COPYRIGHT);
436 if (command != NULL) {
437 /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
438 _PyOS_optind--;
439 argv[_PyOS_optind] = "-c";
442 if (module != NULL) {
443 /* Backup _PyOS_optind and find the real file */
444 struct filedescr *fdescr = NULL;
445 _PyOS_optind--;
446 if ((fdescr = FindModule(module, &fp, &filename))) {
447 argv[_PyOS_optind] = filename;
448 } else {
449 fprintf(stderr, "%s: module %s not found\n",
450 argv[0], module);
451 return 2;
453 if (!fp) {
454 fprintf(stderr,
455 "%s: module %s has no associated file\n",
456 argv[0], module);
457 return 2;
459 if (!_PyImport_IsScript(fdescr)) {
460 fprintf(stderr,
461 "%s: module %s not usable as script\n (%s)\n",
462 argv[0], module, filename);
463 return 2;
467 PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
469 if ((inspect || (command == NULL && filename == NULL && module == NULL)) &&
470 isatty(fileno(stdin))) {
471 PyObject *v;
472 v = PyImport_ImportModule("readline");
473 if (v == NULL)
474 PyErr_Clear();
475 else
476 Py_DECREF(v);
479 if (command) {
480 sts = PyRun_SimpleStringFlags(command, &cf) != 0;
481 free(command);
482 } else if (module) {
483 sts = PyRun_AnyFileExFlags(fp, filename, 1, &cf) != 0;
484 free(module);
485 free(filename);
487 else {
488 if (filename == NULL && stdin_is_interactive) {
489 RunStartupFile(&cf);
491 /* XXX */
492 sts = PyRun_AnyFileExFlags(
494 filename == NULL ? "<stdin>" : filename,
495 filename != NULL, &cf) != 0;
498 /* Check this environment variable at the end, to give programs the
499 * opportunity to set it from Python.
501 if (!saw_inspect_flag &&
502 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
504 inspect = 1;
507 if (inspect && stdin_is_interactive &&
508 (filename != NULL || command != NULL || module != NULL))
509 /* XXX */
510 sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
512 Py_Finalize();
513 #ifdef RISCOS
514 if (Py_RISCOSWimpFlag)
515 fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
516 #endif
518 #ifdef __INSURE__
519 /* Insure++ is a memory analysis tool that aids in discovering
520 * memory leaks and other memory problems. On Python exit, the
521 * interned string dictionary is flagged as being in use at exit
522 * (which it is). Under normal circumstances, this is fine because
523 * the memory will be automatically reclaimed by the system. Under
524 * memory debugging, it's a huge source of useless noise, so we
525 * trade off slower shutdown for less distraction in the memory
526 * reports. -baw
528 _Py_ReleaseInternedStrings();
529 #endif /* __INSURE__ */
531 return sts;
534 /* this is gonna seem *real weird*, but if you put some other code between
535 Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
536 while statement in Misc/gdbinit:ppystack */
538 /* Make the *original* argc/argv available to other modules.
539 This is rare, but it is needed by the secureware extension. */
541 void
542 Py_GetArgcArgv(int *argc, char ***argv)
544 *argc = orig_argc;
545 *argv = orig_argv;