1 /* Python interpreter main program */
5 #include "code.h" /* For CO_FUTURE_DIVISION */
12 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
18 #if (defined(PYOS_OS2) && !defined(PYCC_GCC)) || defined(MS_WINDOWS)
19 #define PYTHONHOMEHELP "<prefix>\\lib"
21 #if defined(PYOS_OS2) && defined(PYCC_GCC)
22 #define PYTHONHOMEHELP "<prefix>/Lib"
24 #define PYTHONHOMEHELP "<prefix>/pythonX.X"
31 "Type \"help\", \"copyright\", \"credits\" or \"license\" " \
32 "for more information."
38 /* For Py_GetArgcArgv(); set by main() */
39 static char **orig_argv
;
42 /* command line options */
43 #define BASE_OPTS "3bBc:dEhiJm:OQ:sStuUvVW:xX?"
46 #define PROGRAM_OPTS BASE_OPTS
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
;
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 add user site directory to sys.path; also PYTHONNOUSERSITE\n\
76 -S : don't imply 'import site' on initialization\n\
77 -t : issue warnings about inconsistent tab usage (-tt: issue errors)\n\
79 static char *usage_3
= "\
80 -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x\n\
81 see man page for details on internal buffering relating to '-u'\n\
82 -v : verbose (trace import statements); also PYTHONVERBOSE=x\n\
83 can be supplied multiple times to increase verbosity\n\
84 -V : print the Python version number and exit (also --version)\n\
85 -W arg : warning control; arg is action:message:category:module:lineno\n\
86 -x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
88 static char *usage_4
= "\
89 -3 : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix\n\
90 file : program read from script file\n\
91 - : program read from stdin (default; interactive mode if a tty)\n\
92 arg ...: arguments passed to program in sys.argv[1:]\n\n\
93 Other environment variables:\n\
94 PYTHONSTARTUP: file executed on interactive startup (no default)\n\
95 PYTHONPATH : '%c'-separated list of directories prefixed to the\n\
96 default module search path. The result is sys.path.\n\
98 static char *usage_5
= "\
99 PYTHONHOME : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
100 The default module search path uses %s.\n\
101 PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
102 PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\
107 usage(int exitcode
, char* program
)
109 FILE *f
= exitcode
? stderr
: stdout
;
111 fprintf(f
, usage_line
, program
);
113 fprintf(f
, "Try `python -h' for more information.\n");
118 fprintf(f
, usage_4
, DELIM
);
119 fprintf(f
, usage_5
, DELIM
, PYTHONHOMEHELP
);
123 /* suppress 'error' message */
127 /* STS$M_INHIB_MSG + SS$_ABORT */
136 static void RunStartupFile(PyCompilerFlags
*cf
)
138 char *startup
= Py_GETENV("PYTHONSTARTUP");
139 if (startup
!= NULL
&& startup
[0] != '\0') {
140 FILE *fp
= fopen(startup
, "r");
142 (void) PyRun_SimpleFileExFlags(fp
, startup
, 0, cf
);
148 PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
150 PyErr_SetFromErrnoWithFilename(PyExc_IOError
,
159 static int RunModule(char *module
, int set_argv0
)
161 PyObject
*runpy
, *runmodule
, *runargs
, *result
;
162 runpy
= PyImport_ImportModule("runpy");
164 fprintf(stderr
, "Could not import runpy module\n");
167 runmodule
= PyObject_GetAttrString(runpy
, "_run_module_as_main");
168 if (runmodule
== NULL
) {
169 fprintf(stderr
, "Could not access runpy._run_module_as_main\n");
173 runargs
= Py_BuildValue("(si)", module
, set_argv0
);
174 if (runargs
== NULL
) {
176 "Could not create arguments for runpy._run_module_as_main\n");
178 Py_DECREF(runmodule
);
181 result
= PyObject_Call(runmodule
, runargs
, NULL
);
182 if (result
== NULL
) {
186 Py_DECREF(runmodule
);
188 if (result
== NULL
) {
195 static int RunMainFromImporter(char *filename
)
197 PyObject
*argv0
= NULL
, *importer
= NULL
;
199 if ((argv0
= PyString_FromString(filename
)) &&
200 (importer
= PyImport_GetImporter(argv0
)) &&
201 (importer
->ob_type
!= &PyNullImporter_Type
))
203 /* argv0 is usable as an import source, so
204 put it in sys.path[0] and import __main__ */
205 PyObject
*sys_path
= NULL
;
206 if ((sys_path
= PySys_GetObject("path")) &&
207 !PyList_SetItem(sys_path
, 0, argv0
))
212 return RunModule("__main__", 0) != 0;
216 Py_XDECREF(importer
);
217 if (PyErr_Occurred()) {
228 Py_Main(int argc
, char **argv
)
232 char *command
= NULL
;
233 char *filename
= NULL
;
238 int skipfirstline
= 0;
239 int stdin_is_interactive
= 0;
242 int saw_unbuffered_flag
= 0;
247 orig_argc
= argc
; /* For Py_GetArgcArgv() */
251 Py_RISCOSWimpFlag
= 0;
254 PySys_ResetWarnOptions();
256 while ((c
= _PyOS_GetOpt(argc
, argv
, PROGRAM_OPTS
)) != EOF
) {
258 /* -c is the last option; following arguments
259 that look like options are left for the
260 command to interpret. */
261 command
= (char *)malloc(strlen(_PyOS_optarg
) + 2);
264 "not enough memory to copy -c argument");
265 strcpy(command
, _PyOS_optarg
);
266 strcat(command
, "\n");
271 /* -m is the last option; following arguments
272 that look like options are left for the
273 module to interpret. */
274 module
= (char *)malloc(strlen(_PyOS_optarg
) + 2);
277 "not enough memory to copy -m argument");
278 strcpy(module
, _PyOS_optarg
);
284 Py_BytesWarningFlag
++;
292 Py_Py3kWarningFlag
++;
293 if (!Py_DivisionWarningFlag
)
294 Py_DivisionWarningFlag
= 1;
298 if (strcmp(_PyOS_optarg
, "old") == 0) {
299 Py_DivisionWarningFlag
= 0;
302 if (strcmp(_PyOS_optarg
, "warn") == 0) {
303 Py_DivisionWarningFlag
= 1;
306 if (strcmp(_PyOS_optarg
, "warnall") == 0) {
307 Py_DivisionWarningFlag
= 2;
310 if (strcmp(_PyOS_optarg
, "new") == 0) {
311 /* This only affects __main__ */
312 cf
.cf_flags
|= CO_FUTURE_DIVISION
;
313 /* And this tells the eval loop to treat
314 BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
319 "-Q option should be `-Qold', "
320 "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
321 return usage(2, argv
[0]);
326 Py_InteractiveFlag
++;
329 /* case 'J': reserved for Jython */
336 Py_DontWriteBytecodeFlag
++;
340 Py_NoUserSiteDirectory
++;
348 Py_IgnoreEnvironmentFlag
++;
357 saw_unbuffered_flag
= 1;
366 Py_RISCOSWimpFlag
= 1;
374 /* case 'X': reserved for implementation-specific arguments */
388 PySys_AddWarnOption(_PyOS_optarg
);
391 /* This space reserved for other options */
394 return usage(2, argv
[0]);
401 return usage(0, argv
[0]);
404 fprintf(stderr
, "Python %s\n", PY_VERSION
);
408 if (Py_Py3kWarningFlag
&& !Py_TabcheckFlag
)
409 /* -3 implies -t (but not -tt) */
412 if (!Py_InspectFlag
&&
413 (p
= Py_GETENV("PYTHONINSPECT")) && *p
!= '\0')
415 if (!saw_unbuffered_flag
&&
416 (p
= Py_GETENV("PYTHONUNBUFFERED")) && *p
!= '\0')
419 if (!Py_NoUserSiteDirectory
&&
420 (p
= Py_GETENV("PYTHONNOUSERSITE")) && *p
!= '\0')
421 Py_NoUserSiteDirectory
= 1;
423 if (command
== NULL
&& module
== NULL
&& _PyOS_optind
< argc
&&
424 strcmp(argv
[_PyOS_optind
], "-") != 0)
427 filename
= decc$
translate_vms(argv
[_PyOS_optind
]);
428 if (filename
== (char *)0 || filename
== (char *)-1)
429 filename
= argv
[_PyOS_optind
];
432 filename
= argv
[_PyOS_optind
];
436 stdin_is_interactive
= Py_FdIsInteractive(stdin
, (char *)0);
439 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
440 _setmode(fileno(stdin
), O_BINARY
);
441 _setmode(fileno(stdout
), O_BINARY
);
444 setvbuf(stdin
, (char *)NULL
, _IONBF
, BUFSIZ
);
445 setvbuf(stdout
, (char *)NULL
, _IONBF
, BUFSIZ
);
446 setvbuf(stderr
, (char *)NULL
, _IONBF
, BUFSIZ
);
447 #else /* !HAVE_SETVBUF */
448 setbuf(stdin
, (char *)NULL
);
449 setbuf(stdout
, (char *)NULL
);
450 setbuf(stderr
, (char *)NULL
);
451 #endif /* !HAVE_SETVBUF */
453 else if (Py_InteractiveFlag
) {
455 /* Doesn't have to have line-buffered -- use unbuffered */
456 /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
457 setvbuf(stdout
, (char *)NULL
, _IONBF
, BUFSIZ
);
458 #else /* !MS_WINDOWS */
460 setvbuf(stdin
, (char *)NULL
, _IOLBF
, BUFSIZ
);
461 setvbuf(stdout
, (char *)NULL
, _IOLBF
, BUFSIZ
);
462 #endif /* HAVE_SETVBUF */
463 #endif /* !MS_WINDOWS */
464 /* Leave stderr alone - it should be unbuffered anyway. */
468 setvbuf (stdout
, (char *)NULL
, _IOLBF
, BUFSIZ
);
473 /* On MacOS X, when the Python interpreter is embedded in an
474 application bundle, it gets executed by a bootstrapping script
475 that does os.execve() with an argv[0] that's different from the
476 actual Python executable. This is needed to keep the Finder happy,
477 or rather, to work around Apple's overly strict requirements of
478 the process name. However, we still need a usable sys.executable,
479 so the actual executable path is passed in an environment variable.
480 See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
482 if ((p
= Py_GETENV("PYTHONEXECUTABLE")) && *p
!= '\0')
483 Py_SetProgramName(p
);
485 Py_SetProgramName(argv
[0]);
487 Py_SetProgramName(argv
[0]);
491 if (Py_VerboseFlag
||
492 (command
== NULL
&& filename
== NULL
&& module
== NULL
&& stdin_is_interactive
)) {
493 fprintf(stderr
, "Python %s on %s\n",
494 Py_GetVersion(), Py_GetPlatform());
496 fprintf(stderr
, "%s\n", COPYRIGHT
);
499 if (command
!= NULL
) {
500 /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
502 argv
[_PyOS_optind
] = "-c";
505 if (module
!= NULL
) {
506 /* Backup _PyOS_optind and force sys.argv[0] = '-c'
507 so that PySys_SetArgv correctly sets sys.path[0] to ''*/
509 argv
[_PyOS_optind
] = "-c";
512 PySys_SetArgv(argc
-_PyOS_optind
, argv
+_PyOS_optind
);
514 if ((Py_InspectFlag
|| (command
== NULL
&& filename
== NULL
&& module
== NULL
)) &&
515 isatty(fileno(stdin
))) {
517 v
= PyImport_ImportModule("readline");
525 sts
= PyRun_SimpleStringFlags(command
, &cf
) != 0;
528 sts
= RunModule(module
, 1);
533 if (filename
== NULL
&& stdin_is_interactive
) {
534 Py_InspectFlag
= 0; /* do exit on SystemExit */
539 sts
= -1; /* keep track of whether we've already run __main__ */
541 if (filename
!= NULL
) {
542 sts
= RunMainFromImporter(filename
);
545 if (sts
==-1 && filename
!=NULL
) {
546 if ((fp
= fopen(filename
, "r")) == NULL
) {
547 fprintf(stderr
, "%s: can't open file '%s': [Errno %d] %s\n",
548 argv
[0], filename
, errno
, strerror(errno
));
552 else if (skipfirstline
) {
554 /* Push back first newline so line numbers
556 while ((ch
= getc(fp
)) != EOF
) {
558 (void)ungetc(ch
, fp
);
564 /* XXX: does this work on Win/Win64? (see posix_fstat) */
566 if (fstat(fileno(fp
), &sb
) == 0 &&
567 S_ISDIR(sb
.st_mode
)) {
568 fprintf(stderr
, "%s: '%s' is a directory, cannot continue\n", argv
[0], filename
);
576 sts
= PyRun_AnyFileExFlags(
578 filename
== NULL
? "<stdin>" : filename
,
579 filename
!= NULL
, &cf
) != 0;
584 /* Check this environment variable at the end, to give programs the
585 * opportunity to set it from Python.
587 if (!Py_InspectFlag
&&
588 (p
= Py_GETENV("PYTHONINSPECT")) && *p
!= '\0')
593 if (Py_InspectFlag
&& stdin_is_interactive
&&
594 (filename
!= NULL
|| command
!= NULL
|| module
!= NULL
)) {
597 sts
= PyRun_AnyFileFlags(stdin
, "<stdin>", &cf
) != 0;
602 if (Py_RISCOSWimpFlag
)
603 fprintf(stderr
, "\x0cq\x0c"); /* make frontend quit */
607 /* Insure++ is a memory analysis tool that aids in discovering
608 * memory leaks and other memory problems. On Python exit, the
609 * interned string dictionary is flagged as being in use at exit
610 * (which it is). Under normal circumstances, this is fine because
611 * the memory will be automatically reclaimed by the system. Under
612 * memory debugging, it's a huge source of useless noise, so we
613 * trade off slower shutdown for less distraction in the memory
616 _Py_ReleaseInternedStrings();
617 #endif /* __INSURE__ */
622 /* this is gonna seem *real weird*, but if you put some other code between
623 Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
624 while statement in Misc/gdbinit:ppystack */
626 /* Make the *original* argc/argv available to other modules.
627 This is rare, but it is needed by the secureware extension. */
630 Py_GetArgcArgv(int *argc
, char ***argv
)