Line data Source code
1 : /* Python interpreter main program */
2 :
3 : #include "Python.h"
4 : #include "osdefs.h"
5 :
6 : #include <locale.h>
7 :
8 : #ifdef __VMS
9 : #error "PEP 11: VMS is now unsupported, code will be removed in Python 3.4"
10 : #include <unixlib.h>
11 : #endif
12 :
13 : #if defined(MS_WINDOWS) || defined(__CYGWIN__)
14 : #include <windows.h>
15 : #ifdef HAVE_FCNTL_H
16 : #include <fcntl.h>
17 : #define PATH_MAX MAXPATHLEN
18 : #endif
19 : #endif
20 :
21 : #ifdef _MSC_VER
22 : #include <crtdbg.h>
23 : #endif
24 :
25 : #if (defined(PYOS_OS2) && !defined(PYCC_GCC)) || defined(MS_WINDOWS)
26 : #define PYTHONHOMEHELP "<prefix>\\lib"
27 : #else
28 : #if defined(PYOS_OS2) && defined(PYCC_GCC)
29 : #define PYTHONHOMEHELP "<prefix>/Lib"
30 : #else
31 : #define PYTHONHOMEHELP "<prefix>/pythonX.X"
32 : #endif
33 : #endif
34 :
35 : #include "pygetopt.h"
36 :
37 : #define COPYRIGHT \
38 : "Type \"help\", \"copyright\", \"credits\" or \"license\" " \
39 : "for more information."
40 :
41 : #ifdef __cplusplus
42 : extern "C" {
43 : #endif
44 :
45 : /* For Py_GetArgcArgv(); set by main() */
46 : static wchar_t **orig_argv;
47 : static int orig_argc;
48 :
49 : /* command line options */
50 : #define BASE_OPTS L"bBc:dEhiJm:OqRsStuvVW:xX:?"
51 :
52 : #define PROGRAM_OPTS BASE_OPTS
53 :
54 : /* Short usage message (with %s for argv0) */
55 : static char *usage_line =
56 : "usage: %ls [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
57 :
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\
68 : ";
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 : -q : don't print version and copyright messages on interactive startup\n\
76 : -s : don't add user site directory to sys.path; also PYTHONNOUSERSITE\n\
77 : -S : don't imply 'import site' on initialization\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 : -X opt : set implementation-specific option\n\
89 : ";
90 : static char *usage_4 = "\
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 : "PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.\n\
105 : ";
106 : static char *usage_6 = "\
107 : PYTHONHASHSEED: if this variable is set to 'random', a random value is used\n\
108 : to seed the hashes of str, bytes and datetime objects. It can also be\n\
109 : set to an integer in the range [0,4294967295] to get hash values with a\n\
110 : predictable seed.\n\
111 : ";
112 :
113 : static int
114 0 : usage(int exitcode, wchar_t* program)
115 : {
116 0 : FILE *f = exitcode ? stderr : stdout;
117 :
118 0 : fprintf(f, usage_line, program);
119 0 : if (exitcode)
120 0 : fprintf(f, "Try `python -h' for more information.\n");
121 : else {
122 0 : fputs(usage_1, f);
123 0 : fputs(usage_2, f);
124 0 : fputs(usage_3, f);
125 0 : fprintf(f, usage_4, DELIM);
126 0 : fprintf(f, usage_5, DELIM, PYTHONHOMEHELP);
127 0 : fputs(usage_6, f);
128 : }
129 : #if defined(__VMS)
130 : if (exitcode == 0) {
131 : /* suppress 'error' message */
132 : return 1;
133 : }
134 : else {
135 : /* STS$M_INHIB_MSG + SS$_ABORT */
136 : return 0x1000002c;
137 : }
138 : #else
139 0 : return exitcode;
140 : #endif
141 : /*NOTREACHED*/
142 : }
143 :
144 0 : static void RunStartupFile(PyCompilerFlags *cf)
145 : {
146 0 : char *startup = Py_GETENV("PYTHONSTARTUP");
147 0 : if (startup != NULL && startup[0] != '\0') {
148 0 : FILE *fp = fopen(startup, "r");
149 0 : if (fp != NULL) {
150 0 : (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
151 0 : PyErr_Clear();
152 0 : fclose(fp);
153 : } else {
154 : int save_errno;
155 :
156 0 : save_errno = errno;
157 0 : PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
158 0 : errno = save_errno;
159 0 : PyErr_SetFromErrnoWithFilename(PyExc_IOError,
160 : startup);
161 0 : PyErr_Print();
162 0 : PyErr_Clear();
163 : }
164 : }
165 0 : }
166 :
167 :
168 0 : static int RunModule(wchar_t *modname, int set_argv0)
169 : {
170 : PyObject *module, *runpy, *runmodule, *runargs, *result;
171 0 : runpy = PyImport_ImportModule("runpy");
172 0 : if (runpy == NULL) {
173 0 : fprintf(stderr, "Could not import runpy module\n");
174 0 : return -1;
175 : }
176 0 : runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main");
177 0 : if (runmodule == NULL) {
178 0 : fprintf(stderr, "Could not access runpy._run_module_as_main\n");
179 0 : Py_DECREF(runpy);
180 0 : return -1;
181 : }
182 0 : module = PyUnicode_FromWideChar(modname, wcslen(modname));
183 0 : if (module == NULL) {
184 0 : fprintf(stderr, "Could not convert module name to unicode\n");
185 0 : Py_DECREF(runpy);
186 0 : Py_DECREF(runmodule);
187 0 : return -1;
188 : }
189 0 : runargs = Py_BuildValue("(Oi)", module, set_argv0);
190 0 : if (runargs == NULL) {
191 0 : fprintf(stderr,
192 : "Could not create arguments for runpy._run_module_as_main\n");
193 0 : Py_DECREF(runpy);
194 0 : Py_DECREF(runmodule);
195 0 : Py_DECREF(module);
196 0 : return -1;
197 : }
198 0 : result = PyObject_Call(runmodule, runargs, NULL);
199 0 : if (result == NULL) {
200 0 : PyErr_Print();
201 : }
202 0 : Py_DECREF(runpy);
203 0 : Py_DECREF(runmodule);
204 0 : Py_DECREF(module);
205 0 : Py_DECREF(runargs);
206 0 : if (result == NULL) {
207 0 : return -1;
208 : }
209 0 : Py_DECREF(result);
210 0 : return 0;
211 : }
212 :
213 : static int
214 0 : RunMainFromImporter(wchar_t *filename)
215 : {
216 0 : PyObject *argv0 = NULL, *importer, *sys_path;
217 : int sts;
218 :
219 0 : argv0 = PyUnicode_FromWideChar(filename, wcslen(filename));
220 0 : if (argv0 == NULL)
221 0 : goto error;
222 :
223 0 : importer = PyImport_GetImporter(argv0);
224 0 : if (importer == NULL)
225 0 : goto error;
226 :
227 0 : if (importer == Py_None) {
228 0 : Py_DECREF(argv0);
229 0 : Py_DECREF(importer);
230 0 : return -1;
231 : }
232 0 : Py_DECREF(importer);
233 :
234 : /* argv0 is usable as an import source, so put it in sys.path[0]
235 : and import __main__ */
236 0 : sys_path = PySys_GetObject("path");
237 0 : if (sys_path == NULL)
238 0 : goto error;
239 0 : if (PyList_SetItem(sys_path, 0, argv0)) {
240 0 : argv0 = NULL;
241 0 : goto error;
242 : }
243 0 : Py_INCREF(argv0);
244 :
245 0 : sts = RunModule(L"__main__", 0);
246 0 : return sts != 0;
247 :
248 : error:
249 0 : Py_XDECREF(argv0);
250 0 : PyErr_Print();
251 0 : return 1;
252 : }
253 :
254 : static int
255 0 : run_command(wchar_t *command, PyCompilerFlags *cf)
256 : {
257 : PyObject *unicode, *bytes;
258 : int ret;
259 :
260 0 : unicode = PyUnicode_FromWideChar(command, -1);
261 0 : if (unicode == NULL)
262 0 : goto error;
263 0 : bytes = PyUnicode_AsUTF8String(unicode);
264 0 : Py_DECREF(unicode);
265 0 : if (bytes == NULL)
266 0 : goto error;
267 0 : ret = PyRun_SimpleStringFlags(PyBytes_AsString(bytes), cf);
268 0 : Py_DECREF(bytes);
269 0 : return ret != 0;
270 :
271 : error:
272 0 : PySys_WriteStderr("Unable to decode the command from the command line:\n");
273 0 : PyErr_Print();
274 0 : return 1;
275 : }
276 :
277 : static int
278 0 : run_file(FILE *fp, const wchar_t *filename, PyCompilerFlags *p_cf)
279 : {
280 0 : PyObject *unicode, *bytes = NULL;
281 : char *filename_str;
282 : int run;
283 :
284 : /* call pending calls like signal handlers (SIGINT) */
285 0 : if (Py_MakePendingCalls() == -1) {
286 0 : PyErr_Print();
287 0 : return 1;
288 : }
289 :
290 0 : if (filename) {
291 0 : unicode = PyUnicode_FromWideChar(filename, wcslen(filename));
292 0 : if (unicode != NULL) {
293 0 : bytes = PyUnicode_EncodeFSDefault(unicode);
294 0 : Py_DECREF(unicode);
295 : }
296 0 : if (bytes != NULL)
297 0 : filename_str = PyBytes_AsString(bytes);
298 : else {
299 0 : PyErr_Clear();
300 0 : filename_str = "<encoding error>";
301 : }
302 : }
303 : else
304 0 : filename_str = "<stdin>";
305 :
306 0 : run = PyRun_AnyFileExFlags(fp, filename_str, filename != NULL, p_cf);
307 0 : Py_XDECREF(bytes);
308 0 : return run != 0;
309 : }
310 :
311 :
312 : /* Main program */
313 :
314 : int
315 0 : Py_Main(int argc, wchar_t **argv)
316 : {
317 : int c;
318 : int sts;
319 0 : wchar_t *command = NULL;
320 0 : wchar_t *filename = NULL;
321 0 : wchar_t *module = NULL;
322 0 : FILE *fp = stdin;
323 : char *p;
324 : #ifdef MS_WINDOWS
325 : wchar_t *wp;
326 : #endif
327 0 : int skipfirstline = 0;
328 0 : int stdin_is_interactive = 0;
329 0 : int help = 0;
330 0 : int version = 0;
331 0 : int saw_unbuffered_flag = 0;
332 : PyCompilerFlags cf;
333 :
334 0 : cf.cf_flags = 0;
335 :
336 0 : orig_argc = argc; /* For Py_GetArgcArgv() */
337 0 : orig_argv = argv;
338 :
339 : /* Hash randomization needed early for all string operations
340 : (including -W and -X options). */
341 0 : while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
342 0 : if (c == 'm' || c == 'c') {
343 : /* -c / -m is the last option: following arguments are
344 : not interpreter options. */
345 : break;
346 : }
347 0 : if (c == 'E') {
348 0 : Py_IgnoreEnvironmentFlag++;
349 0 : break;
350 : }
351 : }
352 :
353 0 : Py_HashRandomizationFlag = 1;
354 0 : _PyRandom_Init();
355 :
356 0 : PySys_ResetWarnOptions();
357 0 : _PyOS_ResetGetOpt();
358 :
359 0 : while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
360 0 : if (c == 'c') {
361 : size_t len;
362 : /* -c is the last option; following arguments
363 : that look like options are left for the
364 : command to interpret. */
365 :
366 0 : len = wcslen(_PyOS_optarg) + 1 + 1;
367 0 : command = (wchar_t *)malloc(sizeof(wchar_t) * len);
368 0 : if (command == NULL)
369 0 : Py_FatalError(
370 : "not enough memory to copy -c argument");
371 0 : wcscpy(command, _PyOS_optarg);
372 0 : command[len - 2] = '\n';
373 0 : command[len - 1] = 0;
374 0 : break;
375 : }
376 :
377 0 : if (c == 'm') {
378 : /* -m is the last option; following arguments
379 : that look like options are left for the
380 : module to interpret. */
381 0 : module = _PyOS_optarg;
382 0 : break;
383 : }
384 :
385 0 : switch (c) {
386 : case 'b':
387 0 : Py_BytesWarningFlag++;
388 0 : break;
389 :
390 : case 'd':
391 0 : Py_DebugFlag++;
392 0 : break;
393 :
394 : case 'i':
395 0 : Py_InspectFlag++;
396 0 : Py_InteractiveFlag++;
397 0 : break;
398 :
399 : /* case 'J': reserved for Jython */
400 :
401 : case 'O':
402 0 : Py_OptimizeFlag++;
403 0 : break;
404 :
405 : case 'B':
406 0 : Py_DontWriteBytecodeFlag++;
407 0 : break;
408 :
409 : case 's':
410 0 : Py_NoUserSiteDirectory++;
411 0 : break;
412 :
413 : case 'S':
414 0 : Py_NoSiteFlag++;
415 0 : break;
416 :
417 : case 'E':
418 : /* Already handled above */
419 0 : break;
420 :
421 : case 't':
422 : /* ignored for backwards compatibility */
423 0 : break;
424 :
425 : case 'u':
426 0 : Py_UnbufferedStdioFlag = 1;
427 0 : saw_unbuffered_flag = 1;
428 0 : break;
429 :
430 : case 'v':
431 0 : Py_VerboseFlag++;
432 0 : break;
433 :
434 : case 'x':
435 0 : skipfirstline = 1;
436 0 : break;
437 :
438 : case 'h':
439 : case '?':
440 0 : help++;
441 0 : break;
442 :
443 : case 'V':
444 0 : version++;
445 0 : break;
446 :
447 : case 'W':
448 0 : PySys_AddWarnOption(_PyOS_optarg);
449 0 : break;
450 :
451 : case 'X':
452 0 : PySys_AddXOption(_PyOS_optarg);
453 0 : break;
454 :
455 : case 'q':
456 0 : Py_QuietFlag++;
457 0 : break;
458 :
459 : case 'R':
460 : /* Ignored */
461 0 : break;
462 :
463 : /* This space reserved for other options */
464 :
465 : default:
466 0 : return usage(2, argv[0]);
467 : /*NOTREACHED*/
468 :
469 : }
470 : }
471 :
472 0 : if (help)
473 0 : return usage(0, argv[0]);
474 :
475 0 : if (version) {
476 0 : fprintf(stderr, "Python %s\n", PY_VERSION);
477 0 : return 0;
478 : }
479 :
480 0 : if (!Py_InspectFlag &&
481 0 : (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
482 0 : Py_InspectFlag = 1;
483 0 : if (!saw_unbuffered_flag &&
484 0 : (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
485 0 : Py_UnbufferedStdioFlag = 1;
486 :
487 0 : if (!Py_NoUserSiteDirectory &&
488 0 : (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
489 0 : Py_NoUserSiteDirectory = 1;
490 :
491 : #ifdef MS_WINDOWS
492 : if (!Py_IgnoreEnvironmentFlag && (wp = _wgetenv(L"PYTHONWARNINGS")) &&
493 : *wp != L'\0') {
494 : wchar_t *buf, *warning;
495 :
496 : buf = (wchar_t *)malloc((wcslen(wp) + 1) * sizeof(wchar_t));
497 : if (buf == NULL)
498 : Py_FatalError(
499 : "not enough memory to copy PYTHONWARNINGS");
500 : wcscpy(buf, wp);
501 : for (warning = wcstok(buf, L",");
502 : warning != NULL;
503 : warning = wcstok(NULL, L",")) {
504 : PySys_AddWarnOption(warning);
505 : }
506 : free(buf);
507 : }
508 : #else
509 0 : if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') {
510 : char *buf, *oldloc;
511 : PyObject *unicode;
512 :
513 : /* settle for strtok here as there's no one standard
514 : C89 wcstok */
515 0 : buf = (char *)malloc(strlen(p) + 1);
516 0 : if (buf == NULL)
517 0 : Py_FatalError(
518 : "not enough memory to copy PYTHONWARNINGS");
519 0 : strcpy(buf, p);
520 0 : oldloc = strdup(setlocale(LC_ALL, NULL));
521 0 : setlocale(LC_ALL, "");
522 0 : for (p = strtok(buf, ","); p != NULL; p = strtok(NULL, ",")) {
523 : #ifdef __APPLE__
524 : /* Use utf-8 on Mac OS X */
525 : unicode = PyUnicode_FromString(p);
526 : #else
527 0 : unicode = PyUnicode_DecodeLocale(p, "surrogateescape");
528 : #endif
529 0 : if (unicode == NULL) {
530 : /* ignore errors */
531 0 : PyErr_Clear();
532 0 : continue;
533 : }
534 0 : PySys_AddWarnOptionUnicode(unicode);
535 0 : Py_DECREF(unicode);
536 : }
537 0 : setlocale(LC_ALL, oldloc);
538 0 : free(oldloc);
539 0 : free(buf);
540 : }
541 : #endif
542 :
543 0 : if (command == NULL && module == NULL && _PyOS_optind < argc &&
544 0 : wcscmp(argv[_PyOS_optind], L"-") != 0)
545 : {
546 : #ifdef __VMS
547 : filename = decc$translate_vms(argv[_PyOS_optind]);
548 : if (filename == (char *)0 || filename == (char *)-1)
549 : filename = argv[_PyOS_optind];
550 :
551 : #else
552 0 : filename = argv[_PyOS_optind];
553 : #endif
554 : }
555 :
556 0 : stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
557 :
558 : #if defined(MS_WINDOWS) || defined(__CYGWIN__)
559 : /* don't translate newlines (\r\n <=> \n) */
560 : _setmode(fileno(stdin), O_BINARY);
561 : _setmode(fileno(stdout), O_BINARY);
562 : _setmode(fileno(stderr), O_BINARY);
563 : #endif
564 :
565 0 : if (Py_UnbufferedStdioFlag) {
566 : #ifdef HAVE_SETVBUF
567 0 : setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
568 0 : setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
569 0 : setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
570 : #else /* !HAVE_SETVBUF */
571 : setbuf(stdin, (char *)NULL);
572 : setbuf(stdout, (char *)NULL);
573 : setbuf(stderr, (char *)NULL);
574 : #endif /* !HAVE_SETVBUF */
575 : }
576 0 : else if (Py_InteractiveFlag) {
577 : #ifdef MS_WINDOWS
578 : /* Doesn't have to have line-buffered -- use unbuffered */
579 : /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
580 : setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
581 : #else /* !MS_WINDOWS */
582 : #ifdef HAVE_SETVBUF
583 0 : setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
584 0 : setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
585 : #endif /* HAVE_SETVBUF */
586 : #endif /* !MS_WINDOWS */
587 : /* Leave stderr alone - it should be unbuffered anyway. */
588 : }
589 : #ifdef __VMS
590 : else {
591 : setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
592 : }
593 : #endif /* __VMS */
594 :
595 : #ifdef __APPLE__
596 : /* On MacOS X, when the Python interpreter is embedded in an
597 : application bundle, it gets executed by a bootstrapping script
598 : that does os.execve() with an argv[0] that's different from the
599 : actual Python executable. This is needed to keep the Finder happy,
600 : or rather, to work around Apple's overly strict requirements of
601 : the process name. However, we still need a usable sys.executable,
602 : so the actual executable path is passed in an environment variable.
603 : See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
604 : script. */
605 : if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') {
606 : wchar_t* buffer;
607 : size_t len = strlen(p) + 1;
608 :
609 : buffer = malloc(len * sizeof(wchar_t));
610 : if (buffer == NULL) {
611 : Py_FatalError(
612 : "not enough memory to copy PYTHONEXECUTABLE");
613 : }
614 :
615 : mbstowcs(buffer, p, len);
616 : Py_SetProgramName(buffer);
617 : /* buffer is now handed off - do not free */
618 : } else {
619 : #ifdef WITH_NEXT_FRAMEWORK
620 : char* pyvenv_launcher = getenv("__PYVENV_LAUNCHER__");
621 :
622 : if (pyvenv_launcher && *pyvenv_launcher) {
623 : /* Used by Mac/Tools/pythonw.c to forward
624 : * the argv0 of the stub executable
625 : */
626 : wchar_t* wbuf = _Py_char2wchar(pyvenv_launcher, NULL);
627 :
628 : if (wbuf == NULL) {
629 : Py_FatalError("Cannot decode __PYVENV_LAUNCHER__");
630 : }
631 : Py_SetProgramName(wbuf);
632 :
633 : /* Don't free wbuf, the argument to Py_SetProgramName
634 : * must remain valid until the Py_Finalize is called.
635 : */
636 : } else {
637 : Py_SetProgramName(argv[0]);
638 : }
639 : #else
640 : Py_SetProgramName(argv[0]);
641 : #endif
642 : }
643 : #else
644 0 : Py_SetProgramName(argv[0]);
645 : #endif
646 0 : Py_Initialize();
647 :
648 0 : if (!Py_QuietFlag && (Py_VerboseFlag ||
649 0 : (command == NULL && filename == NULL &&
650 0 : module == NULL && stdin_is_interactive))) {
651 0 : fprintf(stderr, "Python %s on %s\n",
652 : Py_GetVersion(), Py_GetPlatform());
653 0 : if (!Py_NoSiteFlag)
654 0 : fprintf(stderr, "%s\n", COPYRIGHT);
655 : }
656 :
657 0 : if (command != NULL) {
658 : /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
659 0 : _PyOS_optind--;
660 0 : argv[_PyOS_optind] = L"-c";
661 : }
662 :
663 0 : if (module != NULL) {
664 : /* Backup _PyOS_optind and force sys.argv[0] = '-m'*/
665 0 : _PyOS_optind--;
666 0 : argv[_PyOS_optind] = L"-m";
667 : }
668 :
669 0 : PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
670 :
671 0 : if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&
672 0 : isatty(fileno(stdin))) {
673 : PyObject *v;
674 0 : v = PyImport_ImportModule("readline");
675 0 : if (v == NULL)
676 0 : PyErr_Clear();
677 : else
678 0 : Py_DECREF(v);
679 : }
680 :
681 0 : if (command) {
682 0 : sts = run_command(command, &cf);
683 0 : free(command);
684 0 : } else if (module) {
685 0 : sts = (RunModule(module, 1) != 0);
686 : }
687 : else {
688 :
689 0 : if (filename == NULL && stdin_is_interactive) {
690 0 : Py_InspectFlag = 0; /* do exit on SystemExit */
691 0 : RunStartupFile(&cf);
692 : }
693 : /* XXX */
694 :
695 0 : sts = -1; /* keep track of whether we've already run __main__ */
696 :
697 0 : if (filename != NULL) {
698 0 : sts = RunMainFromImporter(filename);
699 : }
700 :
701 0 : if (sts==-1 && filename!=NULL) {
702 0 : fp = _Py_wfopen(filename, L"r");
703 0 : if (fp == NULL) {
704 : char *cfilename_buffer;
705 : const char *cfilename;
706 0 : int err = errno;
707 0 : cfilename_buffer = _Py_wchar2char(filename, NULL);
708 0 : if (cfilename_buffer != NULL)
709 0 : cfilename = cfilename_buffer;
710 : else
711 0 : cfilename = "<unprintable file name>";
712 0 : fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n",
713 : argv[0], cfilename, err, strerror(err));
714 0 : if (cfilename_buffer)
715 0 : PyMem_Free(cfilename_buffer);
716 0 : return 2;
717 : }
718 0 : else if (skipfirstline) {
719 : int ch;
720 : /* Push back first newline so line numbers
721 : remain the same */
722 0 : while ((ch = getc(fp)) != EOF) {
723 0 : if (ch == '\n') {
724 0 : (void)ungetc(ch, fp);
725 0 : break;
726 : }
727 : }
728 : }
729 : {
730 : /* XXX: does this work on Win/Win64? (see posix_fstat) */
731 : struct stat sb;
732 0 : if (fstat(fileno(fp), &sb) == 0 &&
733 0 : S_ISDIR(sb.st_mode)) {
734 0 : fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename);
735 0 : fclose(fp);
736 0 : return 1;
737 : }
738 : }
739 : }
740 :
741 0 : if (sts == -1)
742 0 : sts = run_file(fp, filename, &cf);
743 : }
744 :
745 : /* Check this environment variable at the end, to give programs the
746 : * opportunity to set it from Python.
747 : */
748 0 : if (!Py_InspectFlag &&
749 0 : (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
750 : {
751 0 : Py_InspectFlag = 1;
752 : }
753 :
754 0 : if (Py_InspectFlag && stdin_is_interactive &&
755 0 : (filename != NULL || command != NULL || module != NULL)) {
756 0 : Py_InspectFlag = 0;
757 : /* XXX */
758 0 : sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
759 : }
760 :
761 0 : Py_Finalize();
762 :
763 : #ifdef __INSURE__
764 : /* Insure++ is a memory analysis tool that aids in discovering
765 : * memory leaks and other memory problems. On Python exit, the
766 : * interned string dictionaries are flagged as being in use at exit
767 : * (which it is). Under normal circumstances, this is fine because
768 : * the memory will be automatically reclaimed by the system. Under
769 : * memory debugging, it's a huge source of useless noise, so we
770 : * trade off slower shutdown for less distraction in the memory
771 : * reports. -baw
772 : */
773 : _Py_ReleaseInternedUnicodeStrings();
774 : #endif /* __INSURE__ */
775 :
776 0 : return sts;
777 : }
778 :
779 : /* this is gonna seem *real weird*, but if you put some other code between
780 : Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
781 : while statement in Misc/gdbinit:ppystack */
782 :
783 : /* Make the *original* argc/argv available to other modules.
784 : This is rare, but it is needed by the secureware extension. */
785 :
786 : void
787 0 : Py_GetArgcArgv(int *argc, wchar_t ***argv)
788 : {
789 0 : *argc = orig_argc;
790 0 : *argv = orig_argv;
791 0 : }
792 :
793 : #ifdef __cplusplus
794 : }
795 : #endif
|