• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Python interpreter main program */
2 
3 #include "Python.h"
4 #include "osdefs.h"
5 #include "code.h" /* For CO_FUTURE_DIVISION */
6 #include "import.h"
7 
8 #ifdef __VMS
9 #include <unixlib.h>
10 #endif
11 
12 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
13 #ifdef HAVE_FCNTL_H
14 #include <fcntl.h>
15 #endif
16 #endif
17 
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
27 
28 #include "pygetopt.h"
29 
30 #define COPYRIGHT \
31     "Type \"help\", \"copyright\", \"credits\" or \"license\" " \
32     "for more information."
33 
34 #ifdef __cplusplus
35 extern "C" {
36 #endif
37 
38 /* For Py_GetArgcArgv(); set by main() */
39 static char **orig_argv;
40 static int  orig_argc;
41 
42 /* command line options */
43 #define BASE_OPTS "3bBc:dEhiJm:OQ:sStuUvVW:xX?"
44 
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*/
54 
55 /* Short usage message (with %s for argv0) */
56 static char *usage_line =
57 "usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
58 
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\
68 ";
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\
78 ";
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          also PYTHONWARNINGS=arg\n\
87 -x     : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
88 ";
89 static char *usage_4 = "\
90 -3     : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix\n\
91 file   : program read from script file\n\
92 -      : program read from stdin (default; interactive mode if a tty)\n\
93 arg ...: arguments passed to program in sys.argv[1:]\n\n\
94 Other environment variables:\n\
95 PYTHONSTARTUP: file executed on interactive startup (no default)\n\
96 PYTHONPATH   : '%c'-separated list of directories prefixed to the\n\
97                default module search path.  The result is sys.path.\n\
98 ";
99 static char *usage_5 = "\
100 PYTHONHOME   : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
101                The default module search path uses %s.\n\
102 PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
103 PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\
104 ";
105 
106 
107 static int
usage(int exitcode,char * program)108 usage(int exitcode, char* program)
109 {
110     FILE *f = exitcode ? stderr : stdout;
111 
112     fprintf(f, usage_line, program);
113     if (exitcode)
114         fprintf(f, "Try `python -h' for more information.\n");
115     else {
116         fputs(usage_1, f);
117         fputs(usage_2, f);
118         fputs(usage_3, f);
119         fprintf(f, usage_4, DELIM);
120         fprintf(f, usage_5, DELIM, PYTHONHOMEHELP);
121     }
122 #if defined(__VMS)
123     if (exitcode == 0) {
124         /* suppress 'error' message */
125         return 1;
126     }
127     else {
128         /* STS$M_INHIB_MSG + SS$_ABORT */
129         return 0x1000002c;
130     }
131 #else
132     return exitcode;
133 #endif
134     /*NOTREACHED*/
135 }
136 
RunStartupFile(PyCompilerFlags * cf)137 static void RunStartupFile(PyCompilerFlags *cf)
138 {
139     char *startup = Py_GETENV("PYTHONSTARTUP");
140     if (startup != NULL && startup[0] != '\0') {
141         FILE *fp = fopen(startup, "r");
142         if (fp != NULL) {
143             (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
144             PyErr_Clear();
145             fclose(fp);
146            } else {
147                     int save_errno;
148                     save_errno = errno;
149                     PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
150                     errno = save_errno;
151                     PyErr_SetFromErrnoWithFilename(PyExc_IOError,
152                                                    startup);
153                     PyErr_Print();
154                     PyErr_Clear();
155         }
156     }
157 }
158 
159 
RunModule(char * module,int set_argv0)160 static int RunModule(char *module, int set_argv0)
161 {
162     PyObject *runpy, *runmodule, *runargs, *result;
163     runpy = PyImport_ImportModule("runpy");
164     if (runpy == NULL) {
165         fprintf(stderr, "Could not import runpy module\n");
166         return -1;
167     }
168     runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main");
169     if (runmodule == NULL) {
170         fprintf(stderr, "Could not access runpy._run_module_as_main\n");
171         Py_DECREF(runpy);
172         return -1;
173     }
174     runargs = Py_BuildValue("(si)", module, set_argv0);
175     if (runargs == NULL) {
176         fprintf(stderr,
177             "Could not create arguments for runpy._run_module_as_main\n");
178         Py_DECREF(runpy);
179         Py_DECREF(runmodule);
180         return -1;
181     }
182     result = PyObject_Call(runmodule, runargs, NULL);
183     if (result == NULL) {
184         PyErr_Print();
185     }
186     Py_DECREF(runpy);
187     Py_DECREF(runmodule);
188     Py_DECREF(runargs);
189     if (result == NULL) {
190         return -1;
191     }
192     Py_DECREF(result);
193     return 0;
194 }
195 
RunMainFromImporter(char * filename)196 static int RunMainFromImporter(char *filename)
197 {
198     PyObject *argv0 = NULL, *importer = NULL;
199 
200     if ((argv0 = PyString_FromString(filename)) &&
201         (importer = PyImport_GetImporter(argv0)) &&
202         (importer->ob_type != &PyNullImporter_Type))
203     {
204              /* argv0 is usable as an import source, so
205                     put it in sys.path[0] and import __main__ */
206         PyObject *sys_path = NULL;
207         if ((sys_path = PySys_GetObject("path")) &&
208             !PyList_SetItem(sys_path, 0, argv0))
209         {
210             Py_INCREF(argv0);
211             Py_DECREF(importer);
212             sys_path = NULL;
213             return RunModule("__main__", 0) != 0;
214         }
215     }
216     Py_XDECREF(argv0);
217     Py_XDECREF(importer);
218     if (PyErr_Occurred()) {
219         PyErr_Print();
220         return 1;
221     }
222     return -1;
223 }
224 
225 
226 /* Main program */
227 
228 int
Py_Main(int argc,char ** argv)229 Py_Main(int argc, char **argv)
230 {
231     int c;
232     int sts;
233     char *command = NULL;
234     char *filename = NULL;
235     char *module = NULL;
236     FILE *fp = stdin;
237     char *p;
238     int unbuffered = 0;
239     int skipfirstline = 0;
240     int stdin_is_interactive = 0;
241     int help = 0;
242     int version = 0;
243     int saw_unbuffered_flag = 0;
244     PyCompilerFlags cf;
245 
246     cf.cf_flags = 0;
247 
248     orig_argc = argc;           /* For Py_GetArgcArgv() */
249     orig_argv = argv;
250 
251 #ifdef RISCOS
252     Py_RISCOSWimpFlag = 0;
253 #endif
254 
255     PySys_ResetWarnOptions();
256 
257     while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
258         if (c == 'c') {
259             /* -c is the last option; following arguments
260                that look like options are left for the
261                command to interpret. */
262             command = (char *)malloc(strlen(_PyOS_optarg) + 2);
263             if (command == NULL)
264                 Py_FatalError(
265                    "not enough memory to copy -c argument");
266             strcpy(command, _PyOS_optarg);
267             strcat(command, "\n");
268             break;
269         }
270 
271         if (c == 'm') {
272             /* -m is the last option; following arguments
273                that look like options are left for the
274                module to interpret. */
275             module = (char *)malloc(strlen(_PyOS_optarg) + 2);
276             if (module == NULL)
277                 Py_FatalError(
278                    "not enough memory to copy -m argument");
279             strcpy(module, _PyOS_optarg);
280             break;
281         }
282 
283         switch (c) {
284         case 'b':
285             Py_BytesWarningFlag++;
286             break;
287 
288         case 'd':
289             Py_DebugFlag++;
290             break;
291 
292         case '3':
293             Py_Py3kWarningFlag++;
294             if (!Py_DivisionWarningFlag)
295                 Py_DivisionWarningFlag = 1;
296             break;
297 
298         case 'Q':
299             if (strcmp(_PyOS_optarg, "old") == 0) {
300                 Py_DivisionWarningFlag = 0;
301                 break;
302             }
303             if (strcmp(_PyOS_optarg, "warn") == 0) {
304                 Py_DivisionWarningFlag = 1;
305                 break;
306             }
307             if (strcmp(_PyOS_optarg, "warnall") == 0) {
308                 Py_DivisionWarningFlag = 2;
309                 break;
310             }
311             if (strcmp(_PyOS_optarg, "new") == 0) {
312                 /* This only affects __main__ */
313                 cf.cf_flags |= CO_FUTURE_DIVISION;
314                 /* And this tells the eval loop to treat
315                    BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
316                 _Py_QnewFlag = 1;
317                 break;
318             }
319             fprintf(stderr,
320                 "-Q option should be `-Qold', "
321                 "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
322             return usage(2, argv[0]);
323             /* NOTREACHED */
324 
325         case 'i':
326             Py_InspectFlag++;
327             Py_InteractiveFlag++;
328             break;
329 
330         /* case 'J': reserved for Jython */
331 
332         case 'O':
333             Py_OptimizeFlag++;
334             break;
335 
336         case 'B':
337             Py_DontWriteBytecodeFlag++;
338             break;
339 
340         case 's':
341             Py_NoUserSiteDirectory++;
342             break;
343 
344         case 'S':
345             Py_NoSiteFlag++;
346             break;
347 
348         case 'E':
349             Py_IgnoreEnvironmentFlag++;
350             break;
351 
352         case 't':
353             Py_TabcheckFlag++;
354             break;
355 
356         case 'u':
357             unbuffered++;
358             saw_unbuffered_flag = 1;
359             break;
360 
361         case 'v':
362             Py_VerboseFlag++;
363             break;
364 
365 #ifdef RISCOS
366         case 'w':
367             Py_RISCOSWimpFlag = 1;
368             break;
369 #endif
370 
371         case 'x':
372             skipfirstline = 1;
373             break;
374 
375         /* case 'X': reserved for implementation-specific arguments */
376 
377         case 'U':
378             Py_UnicodeFlag++;
379             break;
380         case 'h':
381         case '?':
382             help++;
383             break;
384         case 'V':
385             version++;
386             break;
387 
388         case 'W':
389             PySys_AddWarnOption(_PyOS_optarg);
390             break;
391 
392         /* This space reserved for other options */
393 
394         default:
395             return usage(2, argv[0]);
396             /*NOTREACHED*/
397 
398         }
399     }
400 
401     if (help)
402         return usage(0, argv[0]);
403 
404     if (version) {
405         fprintf(stderr, "Python %s\n", PY_VERSION);
406         return 0;
407     }
408 
409     if (Py_Py3kWarningFlag && !Py_TabcheckFlag)
410         /* -3 implies -t (but not -tt) */
411         Py_TabcheckFlag = 1;
412 
413     if (!Py_InspectFlag &&
414         (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
415         Py_InspectFlag = 1;
416     if (!saw_unbuffered_flag &&
417         (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
418         unbuffered = 1;
419 
420     if (!Py_NoUserSiteDirectory &&
421         (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
422         Py_NoUserSiteDirectory = 1;
423 
424     if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') {
425         char *buf, *warning;
426 
427         buf = (char *)malloc(strlen(p) + 1);
428         if (buf == NULL)
429             Py_FatalError(
430                "not enough memory to copy PYTHONWARNINGS");
431         strcpy(buf, p);
432         for (warning = strtok(buf, ",");
433              warning != NULL;
434              warning = strtok(NULL, ","))
435             PySys_AddWarnOption(warning);
436         free(buf);
437     }
438 
439     if (command == NULL && module == NULL && _PyOS_optind < argc &&
440         strcmp(argv[_PyOS_optind], "-") != 0)
441     {
442 #ifdef __VMS
443         filename = decc$translate_vms(argv[_PyOS_optind]);
444         if (filename == (char *)0 || filename == (char *)-1)
445             filename = argv[_PyOS_optind];
446 
447 #else
448         filename = argv[_PyOS_optind];
449 #endif
450     }
451 
452     stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
453 
454     if (unbuffered) {
455 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
456         _setmode(fileno(stdin), O_BINARY);
457         _setmode(fileno(stdout), O_BINARY);
458 #endif
459 #ifdef HAVE_SETVBUF
460         setvbuf(stdin,  (char *)NULL, _IONBF, BUFSIZ);
461         setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
462         setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
463 #else /* !HAVE_SETVBUF */
464         setbuf(stdin,  (char *)NULL);
465         setbuf(stdout, (char *)NULL);
466         setbuf(stderr, (char *)NULL);
467 #endif /* !HAVE_SETVBUF */
468     }
469     else if (Py_InteractiveFlag) {
470 #ifdef MS_WINDOWS
471         /* Doesn't have to have line-buffered -- use unbuffered */
472         /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
473         setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
474 #else /* !MS_WINDOWS */
475 #ifdef HAVE_SETVBUF
476         setvbuf(stdin,  (char *)NULL, _IOLBF, BUFSIZ);
477         setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
478 #endif /* HAVE_SETVBUF */
479 #endif /* !MS_WINDOWS */
480         /* Leave stderr alone - it should be unbuffered anyway. */
481     }
482 #ifdef __VMS
483     else {
484         setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
485     }
486 #endif /* __VMS */
487 
488 #ifdef __APPLE__
489     /* On MacOS X, when the Python interpreter is embedded in an
490        application bundle, it gets executed by a bootstrapping script
491        that does os.execve() with an argv[0] that's different from the
492        actual Python executable. This is needed to keep the Finder happy,
493        or rather, to work around Apple's overly strict requirements of
494        the process name. However, we still need a usable sys.executable,
495        so the actual executable path is passed in an environment variable.
496        See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
497        script. */
498     if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')
499         Py_SetProgramName(p);
500     else
501         Py_SetProgramName(argv[0]);
502 #else
503     Py_SetProgramName(argv[0]);
504 #endif
505     Py_Initialize();
506 
507     if (Py_VerboseFlag ||
508         (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
509         fprintf(stderr, "Python %s on %s\n",
510             Py_GetVersion(), Py_GetPlatform());
511         if (!Py_NoSiteFlag)
512             fprintf(stderr, "%s\n", COPYRIGHT);
513     }
514 
515     if (command != NULL) {
516         /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
517         _PyOS_optind--;
518         argv[_PyOS_optind] = "-c";
519     }
520 
521     if (module != NULL) {
522         /* Backup _PyOS_optind and force sys.argv[0] = '-c'
523            so that PySys_SetArgv correctly sets sys.path[0] to ''
524            rather than looking for a file called "-m". See
525            tracker issue #8202 for details. */
526         _PyOS_optind--;
527         argv[_PyOS_optind] = "-c";
528     }
529 
530     PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
531 
532     if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&
533         isatty(fileno(stdin))) {
534         PyObject *v;
535         v = PyImport_ImportModule("readline");
536         if (v == NULL)
537             PyErr_Clear();
538         else
539             Py_DECREF(v);
540     }
541 
542     if (command) {
543         sts = PyRun_SimpleStringFlags(command, &cf) != 0;
544         free(command);
545     } else if (module) {
546         sts = RunModule(module, 1);
547         free(module);
548     }
549     else {
550 
551         if (filename == NULL && stdin_is_interactive) {
552             Py_InspectFlag = 0; /* do exit on SystemExit */
553             RunStartupFile(&cf);
554         }
555         /* XXX */
556 
557         sts = -1;               /* keep track of whether we've already run __main__ */
558 
559         if (filename != NULL) {
560             sts = RunMainFromImporter(filename);
561         }
562 
563         if (sts==-1 && filename!=NULL) {
564             if ((fp = fopen(filename, "r")) == NULL) {
565                 fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
566                     argv[0], filename, errno, strerror(errno));
567 
568                 return 2;
569             }
570             else if (skipfirstline) {
571                 int ch;
572                 /* Push back first newline so line numbers
573                    remain the same */
574                 while ((ch = getc(fp)) != EOF) {
575                     if (ch == '\n') {
576                         (void)ungetc(ch, fp);
577                         break;
578                     }
579                 }
580             }
581             {
582                 /* XXX: does this work on Win/Win64? (see posix_fstat) */
583                 struct stat sb;
584                 if (fstat(fileno(fp), &sb) == 0 &&
585                     S_ISDIR(sb.st_mode)) {
586                     fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);
587                     fclose(fp);
588                     return 1;
589                 }
590             }
591         }
592 
593         if (sts==-1) {
594             /* call pending calls like signal handlers (SIGINT) */
595             if (Py_MakePendingCalls() == -1) {
596                 PyErr_Print();
597                 sts = 1;
598             } else {
599                 sts = PyRun_AnyFileExFlags(
600                     fp,
601                     filename == NULL ? "<stdin>" : filename,
602                     filename != NULL, &cf) != 0;
603             }
604         }
605 
606     }
607 
608     /* Check this environment variable at the end, to give programs the
609      * opportunity to set it from Python.
610      */
611     if (!Py_InspectFlag &&
612         (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
613     {
614         Py_InspectFlag = 1;
615     }
616 
617     if (Py_InspectFlag && stdin_is_interactive &&
618         (filename != NULL || command != NULL || module != NULL)) {
619         Py_InspectFlag = 0;
620         /* XXX */
621         sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
622     }
623 
624     Py_Finalize();
625 #ifdef RISCOS
626     if (Py_RISCOSWimpFlag)
627         fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
628 #endif
629 
630 #ifdef __INSURE__
631     /* Insure++ is a memory analysis tool that aids in discovering
632      * memory leaks and other memory problems.  On Python exit, the
633      * interned string dictionary is flagged as being in use at exit
634      * (which it is).  Under normal circumstances, this is fine because
635      * the memory will be automatically reclaimed by the system.  Under
636      * memory debugging, it's a huge source of useless noise, so we
637      * trade off slower shutdown for less distraction in the memory
638      * reports.  -baw
639      */
640     _Py_ReleaseInternedStrings();
641 #endif /* __INSURE__ */
642 
643     return sts;
644 }
645 
646 /* this is gonna seem *real weird*, but if you put some other code between
647    Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
648    while statement in Misc/gdbinit:ppystack */
649 
650 /* Make the *original* argc/argv available to other modules.
651    This is rare, but it is needed by the secureware extension. */
652 
653 void
Py_GetArgcArgv(int * argc,char *** argv)654 Py_GetArgcArgv(int *argc, char ***argv)
655 {
656     *argc = orig_argc;
657     *argv = orig_argv;
658 }
659 
660 #ifdef __cplusplus
661 }
662 #endif
663 
664