]>
git.proxmox.com Git - mirror_edk2.git/blob - AppPkg/Applications/Python/PyMod-2.7.2/Modules/main.c
2 Python interpreter main program.
4 Copyright (c) 2015, Daryl McDaniel. All rights reserved.<BR>
9 #include "code.h" /* For CO_FUTURE_DIVISION */
16 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
22 #if (defined(PYOS_OS2) && !defined(PYCC_GCC)) || defined(MS_WINDOWS)
23 #define PYTHONHOMEHELP "<prefix>\\lib"
25 #if defined(PYOS_OS2) && defined(PYCC_GCC)
26 #define PYTHONHOMEHELP "<prefix>/Lib"
28 #define PYTHONHOMEHELP "<prefix>/pythonX.X"
35 "Type \"help\", \"copyright\", \"credits\" or \"license\" " \
36 "for more information."
42 /* For Py_GetArgcArgv(); set by main() */
43 static char **orig_argv
;
46 /* command line options */
47 #define BASE_OPTS "#3bBc:dEhiJm:OQ:sStuUvVW:xX?"
50 #define PROGRAM_OPTS BASE_OPTS
52 /* extra option saying that we are running under a special task window
53 frontend; especially my_readline will behave different */
54 #define PROGRAM_OPTS BASE_OPTS "w"
55 /* corresponding flag */
56 extern int Py_RISCOSWimpFlag
;
59 /* Short usage message (with %s for argv0) */
60 static char *usage_line
=
61 "usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
63 /* Long usage message, split into parts < 512 bytes */
64 static char *usage_1
= "\
65 Options and arguments (and corresponding environment variables):\n\
66 -# : alias stderr to stdout for platforms without STDERR output.\n\
67 -B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x\n\
68 -c cmd : program passed in as string (terminates option list)\n\
69 -d : debug output from parser; also PYTHONDEBUG=x\n\
70 -E : ignore PYTHON* environment variables (such as PYTHONPATH)\n\
71 -h : print this help message and exit (also --help)\n\
72 -i : inspect interactively after running script; forces a prompt even\n\
74 static char *usage_2
= "\
75 if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n\
76 -m mod : run library module as a script (terminates option list)\n\
77 -O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x\n\
78 -OO : remove doc-strings in addition to the -O optimizations\n\
79 -Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew\n\
80 -s : don't add user site directory to sys.path; also PYTHONNOUSERSITE\n\
81 -S : don't imply 'import site' on initialization\n\
82 -t : issue warnings about inconsistent tab usage (-tt: issue errors)\n\
84 static char *usage_3
= "\
85 -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x\n\
86 see man page for details on internal buffering relating to '-u'\n\
87 -v : verbose (trace import statements); also PYTHONVERBOSE=x\n\
88 can be supplied multiple times to increase verbosity\n\
89 -V : print the Python version number and exit (also --version)\n\
90 -W arg : warning control; arg is action:message:category:module:lineno\n\
91 also PYTHONWARNINGS=arg\n\
92 -x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
94 static char *usage_4
= "\
95 -3 : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix\n\
96 file : program read from script file\n\
97 - : program read from stdin (default; interactive mode if a tty)\n\
98 arg ...: arguments passed to program in sys.argv[1:]\n\n\
99 Other environment variables:\n\
100 PYTHONSTARTUP: file executed on interactive startup (no default)\n\
101 PYTHONPATH : '%c'-separated list of directories prefixed to the\n\
102 default module search path. The result is sys.path.\n\
104 static char *usage_5
= "\
105 PYTHONHOME : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
106 The default module search path uses %s.\n\
107 PYTHONCASEOK : ignore case in 'import' statements (UEFI default).\n\
108 PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\
113 usage(int exitcode
, char* program
)
115 FILE *f
= exitcode
? stderr
: stdout
;
117 fprintf(f
, usage_line
, program
);
119 fprintf(f
, "Try `python -h' for more information.\n");
124 fprintf(f
, usage_4
, DELIM
);
125 fprintf(f
, usage_5
, DELIM
, PYTHONHOMEHELP
);
129 /* suppress 'error' message */
133 /* STS$M_INHIB_MSG + SS$_ABORT */
142 static void RunStartupFile(PyCompilerFlags
*cf
)
144 char *startup
= Py_GETENV("PYTHONSTARTUP");
145 if (startup
!= NULL
&& startup
[0] != '\0') {
146 FILE *fp
= fopen(startup
, "r");
148 (void) PyRun_SimpleFileExFlags(fp
, startup
, 0, cf
);
154 PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
156 PyErr_SetFromErrnoWithFilename(PyExc_IOError
,
165 static int RunModule(char *module
, int set_argv0
)
167 PyObject
*runpy
, *runmodule
, *runargs
, *result
;
168 runpy
= PyImport_ImportModule("runpy");
170 fprintf(stderr
, "Could not import runpy module\n");
173 runmodule
= PyObject_GetAttrString(runpy
, "_run_module_as_main");
174 if (runmodule
== NULL
) {
175 fprintf(stderr
, "Could not access runpy._run_module_as_main\n");
179 runargs
= Py_BuildValue("(si)", module
, set_argv0
);
180 if (runargs
== NULL
) {
182 "Could not create arguments for runpy._run_module_as_main\n");
184 Py_DECREF(runmodule
);
187 result
= PyObject_Call(runmodule
, runargs
, NULL
);
188 if (result
== NULL
) {
192 Py_DECREF(runmodule
);
194 if (result
== NULL
) {
201 static int RunMainFromImporter(char *filename
)
203 PyObject
*argv0
= NULL
, *importer
= NULL
;
205 if ((argv0
= PyString_FromString(filename
)) &&
206 (importer
= PyImport_GetImporter(argv0
)) &&
207 (importer
->ob_type
!= &PyNullImporter_Type
))
209 /* argv0 is usable as an import source, so
210 put it in sys.path[0] and import __main__ */
211 PyObject
*sys_path
= NULL
;
212 if ((sys_path
= PySys_GetObject("path")) &&
213 !PyList_SetItem(sys_path
, 0, argv0
))
218 return RunModule("__main__", 0) != 0;
222 Py_XDECREF(importer
);
223 if (PyErr_Occurred()) {
234 Py_Main(int argc
, char **argv
)
238 char *command
= NULL
;
239 char *filename
= NULL
;
244 int skipfirstline
= 0;
245 int stdin_is_interactive
= 0;
248 int saw_unbuffered_flag
= 0;
249 int saw_pound_flag
= 0;
254 orig_argc
= argc
; /* For Py_GetArgcArgv() */
258 Py_RISCOSWimpFlag
= 0;
261 PySys_ResetWarnOptions();
263 while ((c
= _PyOS_GetOpt(argc
, argv
, PROGRAM_OPTS
)) != EOF
) {
265 /* -c is the last option; following arguments
266 that look like options are left for the
267 command to interpret. */
268 command
= (char *)malloc(strlen(_PyOS_optarg
) + 2);
271 "not enough memory to copy -c argument");
272 strcpy(command
, _PyOS_optarg
);
273 strcat(command
, "\n");
278 /* -m is the last option; following arguments
279 that look like options are left for the
280 module to interpret. */
281 module
= (char *)malloc(strlen(_PyOS_optarg
) + 2);
284 "not enough memory to copy -m argument");
285 strcpy(module
, _PyOS_optarg
);
291 Py_BytesWarningFlag
++;
299 Py_Py3kWarningFlag
++;
300 if (!Py_DivisionWarningFlag
)
301 Py_DivisionWarningFlag
= 1;
305 if (strcmp(_PyOS_optarg
, "old") == 0) {
306 Py_DivisionWarningFlag
= 0;
309 if (strcmp(_PyOS_optarg
, "warn") == 0) {
310 Py_DivisionWarningFlag
= 1;
313 if (strcmp(_PyOS_optarg
, "warnall") == 0) {
314 Py_DivisionWarningFlag
= 2;
317 if (strcmp(_PyOS_optarg
, "new") == 0) {
318 /* This only affects __main__ */
319 cf
.cf_flags
|= CO_FUTURE_DIVISION
;
320 /* And this tells the eval loop to treat
321 BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
326 "-Q option should be `-Qold', "
327 "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
328 return usage(2, argv
[0]);
333 Py_InteractiveFlag
++;
336 /* case 'J': reserved for Jython */
343 Py_DontWriteBytecodeFlag
++;
347 Py_NoUserSiteDirectory
++;
355 Py_IgnoreEnvironmentFlag
++;
364 saw_unbuffered_flag
= 1;
373 Py_RISCOSWimpFlag
= 1;
381 /* case 'X': reserved for implementation-specific arguments */
395 PySys_AddWarnOption(_PyOS_optarg
);
399 if (saw_pound_flag
== 0) {
400 if(freopen("stdout:", "w", stderr
) == NULL
) {
401 puts("ERROR: Unable to reopen stderr as an alias to stdout!");
403 saw_pound_flag
= 0xFF;
407 /* This space reserved for other options */
410 return usage(2, argv
[0]);
417 return usage(0, argv
[0]);
420 fprintf(stderr
, "Python %s\n", PY_VERSION
);
424 if (Py_Py3kWarningFlag
&& !Py_TabcheckFlag
)
425 /* -3 implies -t (but not -tt) */
428 if (!Py_InspectFlag
&&
429 (p
= Py_GETENV("PYTHONINSPECT")) && *p
!= '\0')
431 if (!saw_unbuffered_flag
&&
432 (p
= Py_GETENV("PYTHONUNBUFFERED")) && *p
!= '\0')
435 if (!Py_NoUserSiteDirectory
&&
436 (p
= Py_GETENV("PYTHONNOUSERSITE")) && *p
!= '\0')
437 Py_NoUserSiteDirectory
= 1;
439 if ((p
= Py_GETENV("PYTHONWARNINGS")) && *p
!= '\0') {
442 buf
= (char *)malloc(strlen(p
) + 1);
445 "not enough memory to copy PYTHONWARNINGS");
447 for (warning
= strtok(buf
, ",");
449 warning
= strtok(NULL
, ","))
450 PySys_AddWarnOption(warning
);
454 if (command
== NULL
&& module
== NULL
&& _PyOS_optind
< argc
&&
455 strcmp(argv
[_PyOS_optind
], "-") != 0)
458 filename
= decc$
translate_vms(argv
[_PyOS_optind
]);
459 if (filename
== (char *)0 || filename
== (char *)-1)
460 filename
= argv
[_PyOS_optind
];
463 filename
= argv
[_PyOS_optind
];
467 stdin_is_interactive
= Py_FdIsInteractive(stdin
, (char *)0);
470 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
471 _setmode(fileno(stdin
), O_BINARY
);
472 _setmode(fileno(stdout
), O_BINARY
);
475 setvbuf(stdin
, (char *)NULL
, _IONBF
, BUFSIZ
);
476 setvbuf(stdout
, (char *)NULL
, _IONBF
, BUFSIZ
);
477 setvbuf(stderr
, (char *)NULL
, _IONBF
, BUFSIZ
);
478 #else /* !HAVE_SETVBUF */
479 setbuf(stdin
, (char *)NULL
);
480 setbuf(stdout
, (char *)NULL
);
481 setbuf(stderr
, (char *)NULL
);
482 #endif /* !HAVE_SETVBUF */
484 else if (Py_InteractiveFlag
) {
486 /* Doesn't have to have line-buffered -- use unbuffered */
487 /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
488 setvbuf(stdout
, (char *)NULL
, _IONBF
, BUFSIZ
);
489 #else /* !MS_WINDOWS */
491 setvbuf(stdin
, (char *)NULL
, _IOLBF
, BUFSIZ
);
492 setvbuf(stdout
, (char *)NULL
, _IOLBF
, BUFSIZ
);
493 #endif /* HAVE_SETVBUF */
494 #endif /* !MS_WINDOWS */
495 /* Leave stderr alone - it should be unbuffered anyway. */
499 setvbuf (stdout
, (char *)NULL
, _IOLBF
, BUFSIZ
);
504 /* On MacOS X, when the Python interpreter is embedded in an
505 application bundle, it gets executed by a bootstrapping script
506 that does os.execve() with an argv[0] that's different from the
507 actual Python executable. This is needed to keep the Finder happy,
508 or rather, to work around Apple's overly strict requirements of
509 the process name. However, we still need a usable sys.executable,
510 so the actual executable path is passed in an environment variable.
511 See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
513 if ((p
= Py_GETENV("PYTHONEXECUTABLE")) && *p
!= '\0')
514 Py_SetProgramName(p
);
516 Py_SetProgramName(argv
[0]);
518 Py_SetProgramName(argv
[0]);
522 if (Py_VerboseFlag
||
523 (command
== NULL
&& filename
== NULL
&& module
== NULL
&& stdin_is_interactive
)) {
524 fprintf(stderr
, "Python %s on %s\n",
525 Py_GetVersion(), Py_GetPlatform());
527 fprintf(stderr
, "%s\n", COPYRIGHT
);
530 if (command
!= NULL
) {
531 /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
533 argv
[_PyOS_optind
] = "-c";
536 if (module
!= NULL
) {
537 /* Backup _PyOS_optind and force sys.argv[0] = '-c'
538 so that PySys_SetArgv correctly sets sys.path[0] to ''
539 rather than looking for a file called "-m". See
540 tracker issue #8202 for details. */
542 argv
[_PyOS_optind
] = "-c";
545 PySys_SetArgv(argc
-_PyOS_optind
, argv
+_PyOS_optind
);
547 if ((Py_InspectFlag
|| (command
== NULL
&& filename
== NULL
&& module
== NULL
)) &&
548 isatty(fileno(stdin
))) {
550 v
= PyImport_ImportModule("readline");
558 sts
= PyRun_SimpleStringFlags(command
, &cf
) != 0;
561 sts
= (RunModule(module
, 1) != 0);
566 if (filename
== NULL
&& stdin_is_interactive
) {
567 Py_InspectFlag
= 0; /* do exit on SystemExit */
572 sts
= -1; /* keep track of whether we've already run __main__ */
574 if (filename
!= NULL
) {
575 sts
= RunMainFromImporter(filename
);
578 if (sts
==-1 && filename
!=NULL
) {
579 if ((fp
= fopen(filename
, "r")) == NULL
) {
580 fprintf(stderr
, "%s: can't open file '%s': [Errno %d] %s\n",
581 argv
[0], filename
, errno
, strerror(errno
));
585 else if (skipfirstline
) {
587 /* Push back first newline so line numbers
589 while ((ch
= getc(fp
)) != EOF
) {
591 (void)ungetc(ch
, fp
);
597 /* XXX: does this work on Win/Win64? (see posix_fstat) */
599 if (fstat(fileno(fp
), &sb
) == 0 &&
600 S_ISDIR(sb
.st_mode
)) {
601 fprintf(stderr
, "%s: '%s' is a directory, cannot continue\n", argv
[0], filename
);
609 /* call pending calls like signal handlers (SIGINT) */
610 if (Py_MakePendingCalls() == -1) {
614 sts
= PyRun_AnyFileExFlags(
616 filename
== NULL
? "<stdin>" : filename
,
617 filename
!= NULL
, &cf
) != 0;
623 /* Check this environment variable at the end, to give programs the
624 * opportunity to set it from Python.
626 if (!Py_InspectFlag
&&
627 (p
= Py_GETENV("PYTHONINSPECT")) && *p
!= '\0')
632 if (Py_InspectFlag
&& stdin_is_interactive
&&
633 (filename
!= NULL
|| command
!= NULL
|| module
!= NULL
)) {
636 sts
= PyRun_AnyFileFlags(stdin
, "<stdin>", &cf
) != 0;
641 if (Py_RISCOSWimpFlag
)
642 fprintf(stderr
, "\x0cq\x0c"); /* make frontend quit */
646 /* Insure++ is a memory analysis tool that aids in discovering
647 * memory leaks and other memory problems. On Python exit, the
648 * interned string dictionary is flagged as being in use at exit
649 * (which it is). Under normal circumstances, this is fine because
650 * the memory will be automatically reclaimed by the system. Under
651 * memory debugging, it's a huge source of useless noise, so we
652 * trade off slower shutdown for less distraction in the memory
655 _Py_ReleaseInternedStrings();
656 #endif /* __INSURE__ */
661 /* this is gonna seem *real weird*, but if you put some other code between
662 Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
663 while statement in Misc/gdbinit:ppystack */
665 /* Make the *original* argc/argv available to other modules.
666 This is rare, but it is needed by the secureware extension. */
669 Py_GetArgcArgv(int *argc
, char ***argv
)