Speed-up isinstance() for one easy case.
[python.git] / Modules / main.c
blob0cd879de6df9f72d535d4a350ffbdd90bbe9509c
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 #ifdef HAVE_FCNTL_H
14 #include <fcntl.h>
15 #endif
16 #endif
18 #if (defined(PYOS_OS2) && !defined(PYCC_GCC)) || defined(MS_WINDOWS)
19 #define PYTHONHOMEHELP "<prefix>\\lib"
20 #else
21 #if defined(PYOS_OS2) && defined(PYCC_GCC)
22 #define PYTHONHOMEHELP "<prefix>/Lib"
23 #else
24 #define PYTHONHOMEHELP "<prefix>/pythonX.X"
25 #endif
26 #endif
28 #include "pygetopt.h"
30 #define COPYRIGHT \
31 "Type \"help\", \"copyright\", \"credits\" or \"license\" " \
32 "for more information."
34 #ifdef __cplusplus
35 extern "C" {
36 #endif
38 /* For Py_GetArgcArgv(); set by main() */
39 static char **orig_argv;
40 static int orig_argc;
42 /* command line options */
43 #define BASE_OPTS "3Bc:dEhim:OQ:StuUvVW:xX?"
45 #ifndef RISCOS
46 #define PROGRAM_OPTS BASE_OPTS
47 #else /*RISCOS*/
48 /* extra option saying that we are running under a special task window
49 frontend; especially my_readline will behave different */
50 #define PROGRAM_OPTS BASE_OPTS "w"
51 /* corresponding flag */
52 extern int Py_RISCOSWimpFlag;
53 #endif /*RISCOS*/
55 /* Short usage message (with %s for argv0) */
56 static char *usage_line =
57 "usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
59 /* Long usage message, split into parts < 512 bytes */
60 static char *usage_1 = "\
61 Options and arguments (and corresponding environment variables):\n\
62 -B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x\n\
63 -c cmd : program passed in as string (terminates option list)\n\
64 -d : debug output from parser; also PYTHONDEBUG=x\n\
65 -E : ignore PYTHON* environment variables (such as PYTHONPATH)\n\
66 -h : print this help message and exit (also --help)\n\
67 -i : inspect interactively after running script; forces a prompt even\n\
69 static char *usage_2 = "\
70 if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n\
71 -m mod : run library module as a script (terminates option list)\n\
72 -O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x\n\
73 -OO : remove doc-strings in addition to the -O optimizations\n\
74 -Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew\n\
75 -S : don't imply 'import site' on initialization\n\
76 -t : issue warnings about inconsistent tab usage (-tt: issue errors)\n\
78 static char *usage_3 = "\
79 -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x\n\
80 see man page for details on internal buffering relating to '-u'\n\
81 -v : verbose (trace import statements); also PYTHONVERBOSE=x\n\
82 can be supplied multiple times to increase verbosity\n\
83 -V : print the Python version number and exit (also --version)\n\
84 -W arg : warning control; arg is action:message:category:module:lineno\n\
85 -x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
87 static char *usage_4 = "\
88 -3 : warn about Python 3.x incompatibilities\n\
89 file : program read from script file\n\
90 - : program read from stdin (default; interactive mode if a tty)\n\
91 arg ...: arguments passed to program in sys.argv[1:]\n\n\
92 Other environment variables:\n\
93 PYTHONSTARTUP: file executed on interactive startup (no default)\n\
94 PYTHONPATH : '%c'-separated list of directories prefixed to the\n\
95 default module search path. The result is sys.path.\n\
97 static char *usage_5 = "\
98 PYTHONHOME : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
99 The default module search path uses %s.\n\
100 PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
104 static int
105 usage(int exitcode, char* program)
107 FILE *f = exitcode ? stderr : stdout;
109 fprintf(f, usage_line, program);
110 if (exitcode)
111 fprintf(f, "Try `python -h' for more information.\n");
112 else {
113 fprintf(f, usage_1);
114 fprintf(f, usage_2);
115 fprintf(f, usage_3);
116 fprintf(f, usage_4, DELIM);
117 fprintf(f, usage_5, DELIM, PYTHONHOMEHELP);
119 #if defined(__VMS)
120 if (exitcode == 0) {
121 /* suppress 'error' message */
122 return 1;
124 else {
125 /* STS$M_INHIB_MSG + SS$_ABORT */
126 return 0x1000002c;
128 #else
129 return exitcode;
130 #endif
131 /*NOTREACHED*/
134 static void RunStartupFile(PyCompilerFlags *cf)
136 char *startup = Py_GETENV("PYTHONSTARTUP");
137 if (startup != NULL && startup[0] != '\0') {
138 FILE *fp = fopen(startup, "r");
139 if (fp != NULL) {
140 (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
141 PyErr_Clear();
142 fclose(fp);
148 static int RunModule(char *module, int set_argv0)
150 PyObject *runpy, *runmodule, *runargs, *result;
151 runpy = PyImport_ImportModule("runpy");
152 if (runpy == NULL) {
153 fprintf(stderr, "Could not import runpy module\n");
154 return -1;
156 runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main");
157 if (runmodule == NULL) {
158 fprintf(stderr, "Could not access runpy._run_module_as_main\n");
159 Py_DECREF(runpy);
160 return -1;
162 runargs = Py_BuildValue("(si)", module, set_argv0);
163 if (runargs == NULL) {
164 fprintf(stderr,
165 "Could not create arguments for runpy._run_module_as_main\n");
166 Py_DECREF(runpy);
167 Py_DECREF(runmodule);
168 return -1;
170 result = PyObject_Call(runmodule, runargs, NULL);
171 if (result == NULL) {
172 PyErr_Print();
174 Py_DECREF(runpy);
175 Py_DECREF(runmodule);
176 Py_DECREF(runargs);
177 if (result == NULL) {
178 return -1;
180 Py_DECREF(result);
181 return 0;
184 static int RunMainFromImporter(char *filename)
186 PyObject *argv0 = NULL, *importer = NULL;
188 if ((argv0 = PyString_FromString(filename)) &&
189 (importer = PyImport_GetImporter(argv0)) &&
190 (importer->ob_type != &PyNullImporter_Type))
192 /* argv0 is usable as an import source, so
193 put it in sys.path[0] and import __main__ */
194 PyObject *sys_path = NULL;
195 if ((sys_path = PySys_GetObject("path")) &&
196 !PyList_SetItem(sys_path, 0, argv0))
198 Py_INCREF(argv0);
199 Py_DECREF(importer);
200 sys_path = NULL;
201 return RunModule("__main__", 0) != 0;
204 Py_XDECREF(argv0);
205 Py_XDECREF(importer);
206 if (PyErr_Occurred()) {
207 PyErr_Print();
208 return 1;
210 return -1;
214 /* Wait until threading._shutdown completes, provided
215 the threading module was imported in the first place.
216 The shutdown routine will wait until all non-daemon
217 "threading" threads have completed. */
218 #include "abstract.h"
219 static void
220 WaitForThreadShutdown(void)
222 #ifdef WITH_THREAD
223 PyObject *result;
224 PyThreadState *tstate = PyThreadState_GET();
225 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
226 "threading");
227 if (threading == NULL) {
228 /* threading not imported */
229 PyErr_Clear();
230 return;
232 result = PyObject_CallMethod(threading, "_shutdown", "");
233 if (result == NULL)
234 PyErr_WriteUnraisable(threading);
235 else
236 Py_DECREF(result);
237 Py_DECREF(threading);
238 #endif
241 /* Main program */
244 Py_Main(int argc, char **argv)
246 int c;
247 int sts;
248 char *command = NULL;
249 char *filename = NULL;
250 char *module = NULL;
251 FILE *fp = stdin;
252 char *p;
253 int unbuffered = 0;
254 int skipfirstline = 0;
255 int stdin_is_interactive = 0;
256 int help = 0;
257 int version = 0;
258 int saw_unbuffered_flag = 0;
259 PyCompilerFlags cf;
261 cf.cf_flags = 0;
263 orig_argc = argc; /* For Py_GetArgcArgv() */
264 orig_argv = argv;
266 #ifdef RISCOS
267 Py_RISCOSWimpFlag = 0;
268 #endif
270 PySys_ResetWarnOptions();
272 while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
273 if (c == 'c') {
274 /* -c is the last option; following arguments
275 that look like options are left for the
276 command to interpret. */
277 command = (char *)malloc(strlen(_PyOS_optarg) + 2);
278 if (command == NULL)
279 Py_FatalError(
280 "not enough memory to copy -c argument");
281 strcpy(command, _PyOS_optarg);
282 strcat(command, "\n");
283 break;
286 if (c == 'm') {
287 /* -m is the last option; following arguments
288 that look like options are left for the
289 module to interpret. */
290 module = (char *)malloc(strlen(_PyOS_optarg) + 2);
291 if (module == NULL)
292 Py_FatalError(
293 "not enough memory to copy -m argument");
294 strcpy(module, _PyOS_optarg);
295 break;
298 switch (c) {
300 case 'd':
301 Py_DebugFlag++;
302 break;
304 case '3':
305 Py_Py3kWarningFlag++;
306 break;
308 case 'Q':
309 if (strcmp(_PyOS_optarg, "old") == 0) {
310 Py_DivisionWarningFlag = 0;
311 break;
313 if (strcmp(_PyOS_optarg, "warn") == 0) {
314 Py_DivisionWarningFlag = 1;
315 break;
317 if (strcmp(_PyOS_optarg, "warnall") == 0) {
318 Py_DivisionWarningFlag = 2;
319 break;
321 if (strcmp(_PyOS_optarg, "new") == 0) {
322 /* This only affects __main__ */
323 cf.cf_flags |= CO_FUTURE_DIVISION;
324 /* And this tells the eval loop to treat
325 BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
326 _Py_QnewFlag = 1;
327 break;
329 fprintf(stderr,
330 "-Q option should be `-Qold', "
331 "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
332 return usage(2, argv[0]);
333 /* NOTREACHED */
335 case 'i':
336 Py_InspectFlag++;
337 Py_InteractiveFlag++;
338 break;
340 case 'O':
341 Py_OptimizeFlag++;
342 break;
344 case 'B':
345 Py_DontWriteBytecodeFlag++;
346 break;
348 case 'S':
349 Py_NoSiteFlag++;
350 break;
352 case 'E':
353 Py_IgnoreEnvironmentFlag++;
354 break;
356 case 't':
357 Py_TabcheckFlag++;
358 break;
360 case 'u':
361 unbuffered++;
362 saw_unbuffered_flag = 1;
363 break;
365 case 'v':
366 Py_VerboseFlag++;
367 break;
369 #ifdef RISCOS
370 case 'w':
371 Py_RISCOSWimpFlag = 1;
372 break;
373 #endif
375 case 'x':
376 skipfirstline = 1;
377 break;
379 case 'U':
380 Py_UnicodeFlag++;
381 break;
382 case 'h':
383 case '?':
384 help++;
385 break;
386 case 'V':
387 version++;
388 break;
390 case 'W':
391 PySys_AddWarnOption(_PyOS_optarg);
392 break;
394 /* This space reserved for other options */
396 default:
397 return usage(2, argv[0]);
398 /*NOTREACHED*/
403 if (help)
404 return usage(0, argv[0]);
406 if (version) {
407 fprintf(stderr, "Python %s\n", PY_VERSION);
408 return 0;
411 if (!Py_InspectFlag &&
412 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
413 Py_InspectFlag = 1;
414 if (!saw_unbuffered_flag &&
415 (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
416 unbuffered = 1;
418 if (command == NULL && module == NULL && _PyOS_optind < argc &&
419 strcmp(argv[_PyOS_optind], "-") != 0)
421 #ifdef __VMS
422 filename = decc$translate_vms(argv[_PyOS_optind]);
423 if (filename == (char *)0 || filename == (char *)-1)
424 filename = argv[_PyOS_optind];
426 #else
427 filename = argv[_PyOS_optind];
428 #endif
431 stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
433 if (unbuffered) {
434 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
435 _setmode(fileno(stdin), O_BINARY);
436 _setmode(fileno(stdout), O_BINARY);
437 #endif
438 #ifdef HAVE_SETVBUF
439 setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
440 setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
441 setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
442 #else /* !HAVE_SETVBUF */
443 setbuf(stdin, (char *)NULL);
444 setbuf(stdout, (char *)NULL);
445 setbuf(stderr, (char *)NULL);
446 #endif /* !HAVE_SETVBUF */
448 else if (Py_InteractiveFlag) {
449 #ifdef MS_WINDOWS
450 /* Doesn't have to have line-buffered -- use unbuffered */
451 /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
452 setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
453 #else /* !MS_WINDOWS */
454 #ifdef HAVE_SETVBUF
455 setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
456 setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
457 #endif /* HAVE_SETVBUF */
458 #endif /* !MS_WINDOWS */
459 /* Leave stderr alone - it should be unbuffered anyway. */
461 #ifdef __VMS
462 else {
463 setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
465 #endif /* __VMS */
467 #ifdef __APPLE__
468 /* On MacOS X, when the Python interpreter is embedded in an
469 application bundle, it gets executed by a bootstrapping script
470 that does os.execve() with an argv[0] that's different from the
471 actual Python executable. This is needed to keep the Finder happy,
472 or rather, to work around Apple's overly strict requirements of
473 the process name. However, we still need a usable sys.executable,
474 so the actual executable path is passed in an environment variable.
475 See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
476 script. */
477 if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')
478 Py_SetProgramName(p);
479 else
480 Py_SetProgramName(argv[0]);
481 #else
482 Py_SetProgramName(argv[0]);
483 #endif
484 Py_Initialize();
486 if (Py_VerboseFlag ||
487 (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
488 fprintf(stderr, "Python %s on %s\n",
489 Py_GetVersion(), Py_GetPlatform());
490 if (!Py_NoSiteFlag)
491 fprintf(stderr, "%s\n", COPYRIGHT);
494 if (command != NULL) {
495 /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
496 _PyOS_optind--;
497 argv[_PyOS_optind] = "-c";
500 if (module != NULL) {
501 /* Backup _PyOS_optind and force sys.argv[0] = '-c'
502 so that PySys_SetArgv correctly sets sys.path[0] to ''*/
503 _PyOS_optind--;
504 argv[_PyOS_optind] = "-c";
507 PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
509 if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&
510 isatty(fileno(stdin))) {
511 PyObject *v;
512 v = PyImport_ImportModule("readline");
513 if (v == NULL)
514 PyErr_Clear();
515 else
516 Py_DECREF(v);
519 if (command) {
520 sts = PyRun_SimpleStringFlags(command, &cf) != 0;
521 free(command);
522 } else if (module) {
523 sts = RunModule(module, 1);
524 free(module);
526 else {
528 if (filename == NULL && stdin_is_interactive) {
529 Py_InspectFlag = 0; /* do exit on SystemExit */
530 RunStartupFile(&cf);
532 /* XXX */
534 sts = -1; /* keep track of whether we've already run __main__ */
536 if (filename != NULL) {
537 sts = RunMainFromImporter(filename);
540 if (sts==-1 && filename!=NULL) {
541 if ((fp = fopen(filename, "r")) == NULL) {
542 fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
543 argv[0], filename, errno, strerror(errno));
545 return 2;
547 else if (skipfirstline) {
548 int ch;
549 /* Push back first newline so line numbers
550 remain the same */
551 while ((ch = getc(fp)) != EOF) {
552 if (ch == '\n') {
553 (void)ungetc(ch, fp);
554 break;
559 /* XXX: does this work on Win/Win64? (see posix_fstat) */
560 struct stat sb;
561 if (fstat(fileno(fp), &sb) == 0 &&
562 S_ISDIR(sb.st_mode)) {
563 fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);
564 fclose(fp);
565 return 1;
570 if (sts==-1) {
571 sts = PyRun_AnyFileExFlags(
573 filename == NULL ? "<stdin>" : filename,
574 filename != NULL, &cf) != 0;
579 /* Check this environment variable at the end, to give programs the
580 * opportunity to set it from Python.
582 if (!Py_InspectFlag &&
583 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
585 Py_InspectFlag = 1;
588 if (Py_InspectFlag && stdin_is_interactive &&
589 (filename != NULL || command != NULL || module != NULL)) {
590 Py_InspectFlag = 0;
591 /* XXX */
592 sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
595 WaitForThreadShutdown();
597 Py_Finalize();
598 #ifdef RISCOS
599 if (Py_RISCOSWimpFlag)
600 fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
601 #endif
603 #ifdef __INSURE__
604 /* Insure++ is a memory analysis tool that aids in discovering
605 * memory leaks and other memory problems. On Python exit, the
606 * interned string dictionary is flagged as being in use at exit
607 * (which it is). Under normal circumstances, this is fine because
608 * the memory will be automatically reclaimed by the system. Under
609 * memory debugging, it's a huge source of useless noise, so we
610 * trade off slower shutdown for less distraction in the memory
611 * reports. -baw
613 _Py_ReleaseInternedStrings();
614 #endif /* __INSURE__ */
616 return sts;
619 /* this is gonna seem *real weird*, but if you put some other code between
620 Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
621 while statement in Misc/gdbinit:ppystack */
623 /* Make the *original* argc/argv available to other modules.
624 This is rare, but it is needed by the secureware extension. */
626 void
627 Py_GetArgcArgv(int *argc, char ***argv)
629 *argc = orig_argc;
630 *argv = orig_argv;
633 #ifdef __cplusplus
635 #endif