1 /* Python interpreter main program */
13 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
17 #define PATH_MAX MAXPATHLEN
25 #if (defined(PYOS_OS2) && !defined(PYCC_GCC)) || defined(MS_WINDOWS)
26 #define PYTHONHOMEHELP "<prefix>\\lib"
28 #if defined(PYOS_OS2) && defined(PYCC_GCC)
29 #define PYTHONHOMEHELP "<prefix>/Lib"
31 #define PYTHONHOMEHELP "<prefix>/pythonX.X"
38 "Type \"help\", \"copyright\", \"credits\" or \"license\" " \
39 "for more information."
45 /* For Py_GetArgcArgv(); set by main() */
46 static wchar_t **orig_argv
;
49 /* command line options */
50 #define BASE_OPTS L"bBc:dEhiJm:OsStuvVW:xX?"
52 #define PROGRAM_OPTS BASE_OPTS
54 /* Short usage message (with %s for argv0) */
55 static char *usage_line
=
56 "usage: %ls [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
58 /* Long usage message, split into parts < 512 bytes */
59 static char *usage_1
= "\
60 Options and arguments (and corresponding environment variables):\n\
61 -b : issue warnings about str(bytes_instance), str(bytearray_instance)\n\
62 and comparing bytes/bytearray with str. (-bb: issue errors)\n\
63 -B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x\n\
64 -c cmd : program passed in as string (terminates option list)\n\
65 -d : debug output from parser; also PYTHONDEBUG=x\n\
66 -E : ignore PYTHON* environment variables (such as PYTHONPATH)\n\
67 -h : print this help message and exit (also --help)\n\
69 static char *usage_2
= "\
70 -i : inspect interactively after running script; forces a prompt even\n\
71 if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n\
72 -m mod : run library module as a script (terminates option list)\n\
73 -O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x\n\
74 -OO : remove doc-strings in addition to the -O optimizations\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\
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 file : program read from script file\n\
89 - : program read from stdin (default; interactive mode if a tty)\n\
90 arg ...: arguments passed to program in sys.argv[1:]\n\n\
91 Other environment variables:\n\
92 PYTHONSTARTUP: file executed on interactive startup (no default)\n\
93 PYTHONPATH : '%c'-separated list of directories prefixed to the\n\
94 default module search path. The result is sys.path.\n\
96 static char *usage_5
= "\
97 PYTHONHOME : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
98 The default module search path uses %s.\n\
99 PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
100 PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\
105 _wfopen(const wchar_t *path
, const wchar_t *mode
)
107 char cpath
[PATH_MAX
];
110 r
= wcstombs(cpath
, path
, PATH_MAX
);
111 if (r
== (size_t)-1 || r
>= PATH_MAX
) {
115 r
= wcstombs(cmode
, mode
, 10);
116 if (r
== (size_t)-1 || r
>= 10) {
120 return fopen(cpath
, cmode
);
126 usage(int exitcode
, wchar_t* program
)
128 FILE *f
= exitcode
? stderr
: stdout
;
130 fprintf(f
, usage_line
, program
);
132 fprintf(f
, "Try `python -h' for more information.\n");
137 fprintf(f
, usage_4
, DELIM
);
138 fprintf(f
, usage_5
, DELIM
, PYTHONHOMEHELP
);
142 /* suppress 'error' message */
146 /* STS$M_INHIB_MSG + SS$_ABORT */
155 static void RunStartupFile(PyCompilerFlags
*cf
)
157 char *startup
= Py_GETENV("PYTHONSTARTUP");
158 if (startup
!= NULL
&& startup
[0] != '\0') {
159 FILE *fp
= fopen(startup
, "r");
161 (void) PyRun_SimpleFileExFlags(fp
, startup
, 0, cf
);
168 PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
170 PyErr_SetFromErrnoWithFilename(PyExc_IOError
,
179 static int RunModule(wchar_t *modname
, int set_argv0
)
181 PyObject
*module
, *runpy
, *runmodule
, *runargs
, *result
;
182 runpy
= PyImport_ImportModule("runpy");
184 fprintf(stderr
, "Could not import runpy module\n");
187 runmodule
= PyObject_GetAttrString(runpy
, "_run_module_as_main");
188 if (runmodule
== NULL
) {
189 fprintf(stderr
, "Could not access runpy._run_module_as_main\n");
193 module
= PyUnicode_FromWideChar(modname
, wcslen(modname
));
194 if (module
== NULL
) {
195 fprintf(stderr
, "Could not convert module name to unicode\n");
197 Py_DECREF(runmodule
);
200 runargs
= Py_BuildValue("(Oi)", module
, set_argv0
);
201 if (runargs
== NULL
) {
203 "Could not create arguments for runpy._run_module_as_main\n");
205 Py_DECREF(runmodule
);
209 result
= PyObject_Call(runmodule
, runargs
, NULL
);
210 if (result
== NULL
) {
214 Py_DECREF(runmodule
);
217 if (result
== NULL
) {
224 static int RunMainFromImporter(wchar_t *filename
)
226 PyObject
*argv0
= NULL
, *importer
= NULL
;
228 if ((argv0
= PyUnicode_FromWideChar(filename
,wcslen(filename
))) &&
229 (importer
= PyImport_GetImporter(argv0
)) &&
230 (importer
->ob_type
!= &PyNullImporter_Type
))
232 /* argv0 is usable as an import source, so
233 put it in sys.path[0] and import __main__ */
234 PyObject
*sys_path
= NULL
;
235 if ((sys_path
= PySys_GetObject("path")) &&
236 !PyList_SetItem(sys_path
, 0, argv0
))
241 return RunModule(L
"__main__", 0) != 0;
245 Py_XDECREF(importer
);
246 if (PyErr_Occurred()) {
256 /* Wait until threading._shutdown completes, provided
257 the threading module was imported in the first place.
258 The shutdown routine will wait until all non-daemon
259 "threading" threads have completed. */
260 #include "abstract.h"
262 WaitForThreadShutdown(void)
266 PyThreadState
*tstate
= PyThreadState_GET();
267 PyObject
*threading
= PyMapping_GetItemString(tstate
->interp
->modules
,
269 if (threading
== NULL
) {
270 /* threading not imported */
274 result
= PyObject_CallMethod(threading
, "_shutdown", "");
276 PyErr_WriteUnraisable(threading
);
279 Py_DECREF(threading
);
286 Py_Main(int argc
, wchar_t **argv
)
290 wchar_t *command
= NULL
;
291 wchar_t *filename
= NULL
;
292 wchar_t *module
= NULL
;
295 int skipfirstline
= 0;
296 int stdin_is_interactive
= 0;
299 int saw_unbuffered_flag
= 0;
304 orig_argc
= argc
; /* For Py_GetArgcArgv() */
307 PySys_ResetWarnOptions();
309 while ((c
= _PyOS_GetOpt(argc
, argv
, PROGRAM_OPTS
)) != EOF
) {
312 /* -c is the last option; following arguments
313 that look like options are left for the
314 command to interpret. */
316 len
= wcslen(_PyOS_optarg
) + 1 + 1;
317 command
= (wchar_t *)malloc(sizeof(wchar_t) * len
);
320 "not enough memory to copy -c argument");
321 wcscpy(command
, _PyOS_optarg
);
322 command
[len
- 2] = '\n';
323 command
[len
- 1] = 0;
328 /* -m is the last option; following arguments
329 that look like options are left for the
330 module to interpret. */
331 module
= _PyOS_optarg
;
337 Py_BytesWarningFlag
++;
346 Py_InteractiveFlag
++;
349 /* case 'J': reserved for Jython */
356 Py_DontWriteBytecodeFlag
++;
360 Py_NoUserSiteDirectory
++;
368 Py_IgnoreEnvironmentFlag
++;
372 /* ignored for backwards compatibility */
376 Py_UnbufferedStdioFlag
= 1;
377 saw_unbuffered_flag
= 1;
388 /* case 'X': reserved for implementation-specific arguments */
400 PySys_AddWarnOption(_PyOS_optarg
);
403 /* This space reserved for other options */
406 return usage(2, argv
[0]);
413 return usage(0, argv
[0]);
416 fprintf(stderr
, "Python %s\n", PY_VERSION
);
420 if (!Py_InspectFlag
&&
421 (p
= Py_GETENV("PYTHONINSPECT")) && *p
!= '\0')
423 if (!saw_unbuffered_flag
&&
424 (p
= Py_GETENV("PYTHONUNBUFFERED")) && *p
!= '\0')
425 Py_UnbufferedStdioFlag
= 1;
427 if (!Py_NoUserSiteDirectory
&&
428 (p
= Py_GETENV("PYTHONNOUSERSITE")) && *p
!= '\0')
429 Py_NoUserSiteDirectory
= 1;
431 if (command
== NULL
&& module
== NULL
&& _PyOS_optind
< argc
&&
432 wcscmp(argv
[_PyOS_optind
], L
"-") != 0)
435 filename
= decc$
translate_vms(argv
[_PyOS_optind
]);
436 if (filename
== (char *)0 || filename
== (char *)-1)
437 filename
= argv
[_PyOS_optind
];
440 filename
= argv
[_PyOS_optind
];
444 stdin_is_interactive
= Py_FdIsInteractive(stdin
, (char *)0);
446 if (Py_UnbufferedStdioFlag
) {
447 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
448 _setmode(fileno(stdin
), O_BINARY
);
449 _setmode(fileno(stdout
), O_BINARY
);
452 setvbuf(stdin
, (char *)NULL
, _IONBF
, BUFSIZ
);
453 setvbuf(stdout
, (char *)NULL
, _IONBF
, BUFSIZ
);
454 setvbuf(stderr
, (char *)NULL
, _IONBF
, BUFSIZ
);
455 #else /* !HAVE_SETVBUF */
456 setbuf(stdin
, (char *)NULL
);
457 setbuf(stdout
, (char *)NULL
);
458 setbuf(stderr
, (char *)NULL
);
459 #endif /* !HAVE_SETVBUF */
461 else if (Py_InteractiveFlag
) {
463 /* Doesn't have to have line-buffered -- use unbuffered */
464 /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
465 setvbuf(stdout
, (char *)NULL
, _IONBF
, BUFSIZ
);
466 #else /* !MS_WINDOWS */
468 setvbuf(stdin
, (char *)NULL
, _IOLBF
, BUFSIZ
);
469 setvbuf(stdout
, (char *)NULL
, _IOLBF
, BUFSIZ
);
470 #endif /* HAVE_SETVBUF */
471 #endif /* !MS_WINDOWS */
472 /* Leave stderr alone - it should be unbuffered anyway. */
476 setvbuf (stdout
, (char *)NULL
, _IOLBF
, BUFSIZ
);
481 /* On MacOS X, when the Python interpreter is embedded in an
482 application bundle, it gets executed by a bootstrapping script
483 that does os.execve() with an argv[0] that's different from the
484 actual Python executable. This is needed to keep the Finder happy,
485 or rather, to work around Apple's overly strict requirements of
486 the process name. However, we still need a usable sys.executable,
487 so the actual executable path is passed in an environment variable.
488 See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
490 if ((p
= Py_GETENV("PYTHONEXECUTABLE")) && *p
!= '\0') {
492 size_t len
= strlen(p
);
495 buffer
= malloc(len
* sizeof(wchar_t));
496 if (buffer
== NULL
) {
498 "not enough memory to copy PYTHONEXECUTABLE");
501 r
= mbstowcs(buffer
, p
, len
);
502 Py_SetProgramName(buffer
);
503 /* buffer is now handed off - do not free */
505 Py_SetProgramName(argv
[0]);
508 Py_SetProgramName(argv
[0]);
512 if (Py_VerboseFlag
||
513 (command
== NULL
&& filename
== NULL
&& module
== NULL
&& stdin_is_interactive
)) {
514 fprintf(stderr
, "Python %s on %s\n",
515 Py_GetVersion(), Py_GetPlatform());
517 fprintf(stderr
, "%s\n", COPYRIGHT
);
520 if (command
!= NULL
) {
521 /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
523 argv
[_PyOS_optind
] = L
"-c";
526 if (module
!= NULL
) {
527 /* Backup _PyOS_optind and force sys.argv[0] = '-c'
528 so that PySys_SetArgv correctly sets sys.path[0] to ''*/
530 argv
[_PyOS_optind
] = L
"-c";
533 PySys_SetArgv(argc
-_PyOS_optind
, argv
+_PyOS_optind
);
535 if ((Py_InspectFlag
|| (command
== NULL
&& filename
== NULL
&& module
== NULL
)) &&
536 isatty(fileno(stdin
))) {
538 v
= PyImport_ImportModule("readline");
546 PyObject
*commandObj
= PyUnicode_FromWideChar(
547 command
, wcslen(command
));
549 if (commandObj
!= NULL
) {
550 sts
= PyRun_SimpleStringFlags(
551 _PyUnicode_AsString(commandObj
), &cf
) != 0;
557 Py_DECREF(commandObj
);
559 sts
= RunModule(module
, 1);
563 if (filename
== NULL
&& stdin_is_interactive
) {
564 Py_InspectFlag
= 0; /* do exit on SystemExit */
569 sts
= -1; /* keep track of whether we've already run __main__ */
571 if (filename
!= NULL
) {
572 sts
= RunMainFromImporter(filename
);
575 if (sts
==-1 && filename
!=NULL
) {
576 if ((fp
= _wfopen(filename
, L
"r")) == NULL
) {
577 char cfilename
[PATH_MAX
];
578 size_t r
= wcstombs(cfilename
, filename
, PATH_MAX
);
580 /* cfilename is not null-terminated;
581 * forcefully null-terminating it
582 * might break the shift state */
583 strcpy(cfilename
, "<file name too long>");
584 if (r
== ((size_t)-1))
585 strcpy(cfilename
, "<unprintable file name>");
586 fprintf(stderr
, "%ls: can't open file '%s': [Errno %d] %s\n",
587 argv
[0], cfilename
, errno
, strerror(errno
));
591 else if (skipfirstline
) {
593 /* Push back first newline so line numbers
595 while ((ch
= getc(fp
)) != EOF
) {
597 (void)ungetc(ch
, fp
);
603 /* XXX: does this work on Win/Win64? (see posix_fstat) */
605 if (fstat(fileno(fp
), &sb
) == 0 &&
606 S_ISDIR(sb
.st_mode
)) {
607 fprintf(stderr
, "%ls: '%ls' is a directory, cannot continue\n", argv
[0], filename
);
615 PyObject
*filenameObj
= NULL
;
616 char *p_cfilename
= "<stdin>";
618 filenameObj
= PyUnicode_FromWideChar(
619 filename
, wcslen(filename
));
620 if (filenameObj
!= NULL
)
621 p_cfilename
= _PyUnicode_AsString(filenameObj
);
623 p_cfilename
= "<decoding error>";
625 sts
= PyRun_AnyFileExFlags(
628 filename
!= NULL
, &cf
) != 0;
629 Py_XDECREF(filenameObj
);
634 /* Check this environment variable at the end, to give programs the
635 * opportunity to set it from Python.
637 if (!Py_InspectFlag
&&
638 (p
= Py_GETENV("PYTHONINSPECT")) && *p
!= '\0')
643 if (Py_InspectFlag
&& stdin_is_interactive
&&
644 (filename
!= NULL
|| command
!= NULL
|| module
!= NULL
)) {
647 sts
= PyRun_AnyFileFlags(stdin
, "<stdin>", &cf
) != 0;
650 WaitForThreadShutdown();
655 /* Insure++ is a memory analysis tool that aids in discovering
656 * memory leaks and other memory problems. On Python exit, the
657 * interned string dictionaries are flagged as being in use at exit
658 * (which it is). Under normal circumstances, this is fine because
659 * the memory will be automatically reclaimed by the system. Under
660 * memory debugging, it's a huge source of useless noise, so we
661 * trade off slower shutdown for less distraction in the memory
664 _Py_ReleaseInternedStrings();
665 _Py_ReleaseInternedUnicodeStrings();
666 #endif /* __INSURE__ */
671 /* this is gonna seem *real weird*, but if you put some other code between
672 Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
673 while statement in Misc/gdbinit:ppystack */
675 /* Make the *original* argc/argv available to other modules.
676 This is rare, but it is needed by the secureware extension. */
679 Py_GetArgcArgv(int *argc
, wchar_t ***argv
)