Merged revisions 75248 via svnmerge from
[python/dscho.git] / Modules / main.c
blob22794dafb9b7d6788d2883f1f521a7b2ed0d4e55
1 /* Python interpreter main program */
3 #include "Python.h"
4 #include "osdefs.h"
5 #include "import.h"
7 #include <locale.h>
9 #ifdef __VMS
10 #include <unixlib.h>
11 #endif
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
21 #ifdef _MSC_VER
22 #include <crtdbg.h>
23 #endif
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
35 #include "pygetopt.h"
37 #define COPYRIGHT \
38 "Type \"help\", \"copyright\", \"credits\" or \"license\" " \
39 "for more information."
41 #ifdef __cplusplus
42 extern "C" {
43 #endif
45 /* For Py_GetArgcArgv(); set by main() */
46 static wchar_t **orig_argv;
47 static int orig_argc;
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\
103 #ifndef MS_WINDOWS
104 static FILE*
105 _wfopen(const wchar_t *path, const wchar_t *mode)
107 char cpath[PATH_MAX];
108 char cmode[10];
109 size_t r;
110 r = wcstombs(cpath, path, PATH_MAX);
111 if (r == (size_t)-1 || r >= PATH_MAX) {
112 errno = EINVAL;
113 return NULL;
115 r = wcstombs(cmode, mode, 10);
116 if (r == (size_t)-1 || r >= 10) {
117 errno = EINVAL;
118 return NULL;
120 return fopen(cpath, cmode);
122 #endif
125 static int
126 usage(int exitcode, wchar_t* program)
128 FILE *f = exitcode ? stderr : stdout;
130 fprintf(f, usage_line, program);
131 if (exitcode)
132 fprintf(f, "Try `python -h' for more information.\n");
133 else {
134 fputs(usage_1, f);
135 fputs(usage_2, f);
136 fputs(usage_3, f);
137 fprintf(f, usage_4, DELIM);
138 fprintf(f, usage_5, DELIM, PYTHONHOMEHELP);
140 #if defined(__VMS)
141 if (exitcode == 0) {
142 /* suppress 'error' message */
143 return 1;
145 else {
146 /* STS$M_INHIB_MSG + SS$_ABORT */
147 return 0x1000002c;
149 #else
150 return exitcode;
151 #endif
152 /*NOTREACHED*/
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");
160 if (fp != NULL) {
161 (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
162 PyErr_Clear();
163 fclose(fp);
164 } else {
165 int save_errno;
167 save_errno = errno;
168 PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
169 errno = save_errno;
170 PyErr_SetFromErrnoWithFilename(PyExc_IOError,
171 startup);
172 PyErr_Print();
173 PyErr_Clear();
179 static int RunModule(wchar_t *modname, int set_argv0)
181 PyObject *module, *runpy, *runmodule, *runargs, *result;
182 runpy = PyImport_ImportModule("runpy");
183 if (runpy == NULL) {
184 fprintf(stderr, "Could not import runpy module\n");
185 return -1;
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");
190 Py_DECREF(runpy);
191 return -1;
193 module = PyUnicode_FromWideChar(modname, wcslen(modname));
194 if (module == NULL) {
195 fprintf(stderr, "Could not convert module name to unicode\n");
196 Py_DECREF(runpy);
197 Py_DECREF(runmodule);
198 return -1;
200 runargs = Py_BuildValue("(Oi)", module, set_argv0);
201 if (runargs == NULL) {
202 fprintf(stderr,
203 "Could not create arguments for runpy._run_module_as_main\n");
204 Py_DECREF(runpy);
205 Py_DECREF(runmodule);
206 Py_DECREF(module);
207 return -1;
209 result = PyObject_Call(runmodule, runargs, NULL);
210 if (result == NULL) {
211 PyErr_Print();
213 Py_DECREF(runpy);
214 Py_DECREF(runmodule);
215 Py_DECREF(module);
216 Py_DECREF(runargs);
217 if (result == NULL) {
218 return -1;
220 Py_DECREF(result);
221 return 0;
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))
238 Py_INCREF(argv0);
239 Py_DECREF(importer);
240 sys_path = NULL;
241 return RunModule(L"__main__", 0) != 0;
244 Py_XDECREF(argv0);
245 Py_XDECREF(importer);
246 if (PyErr_Occurred()) {
247 PyErr_Print();
248 return 1;
250 else {
251 return -1;
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"
261 static void
262 WaitForThreadShutdown(void)
264 #ifdef WITH_THREAD
265 PyObject *result;
266 PyThreadState *tstate = PyThreadState_GET();
267 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
268 "threading");
269 if (threading == NULL) {
270 /* threading not imported */
271 PyErr_Clear();
272 return;
274 result = PyObject_CallMethod(threading, "_shutdown", "");
275 if (result == NULL)
276 PyErr_WriteUnraisable(threading);
277 else
278 Py_DECREF(result);
279 Py_DECREF(threading);
280 #endif
283 /* Main program */
286 Py_Main(int argc, wchar_t **argv)
288 int c;
289 int sts;
290 wchar_t *command = NULL;
291 wchar_t *filename = NULL;
292 wchar_t *module = NULL;
293 FILE *fp = stdin;
294 char *p;
295 int skipfirstline = 0;
296 int stdin_is_interactive = 0;
297 int help = 0;
298 int version = 0;
299 int saw_unbuffered_flag = 0;
300 PyCompilerFlags cf;
302 cf.cf_flags = 0;
304 orig_argc = argc; /* For Py_GetArgcArgv() */
305 orig_argv = argv;
307 PySys_ResetWarnOptions();
309 while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
310 if (c == 'c') {
311 size_t len;
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);
318 if (command == NULL)
319 Py_FatalError(
320 "not enough memory to copy -c argument");
321 wcscpy(command, _PyOS_optarg);
322 command[len - 2] = '\n';
323 command[len - 1] = 0;
324 break;
327 if (c == 'm') {
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;
332 break;
335 switch (c) {
336 case 'b':
337 Py_BytesWarningFlag++;
338 break;
340 case 'd':
341 Py_DebugFlag++;
342 break;
344 case 'i':
345 Py_InspectFlag++;
346 Py_InteractiveFlag++;
347 break;
349 /* case 'J': reserved for Jython */
351 case 'O':
352 Py_OptimizeFlag++;
353 break;
355 case 'B':
356 Py_DontWriteBytecodeFlag++;
357 break;
359 case 's':
360 Py_NoUserSiteDirectory++;
361 break;
363 case 'S':
364 Py_NoSiteFlag++;
365 break;
367 case 'E':
368 Py_IgnoreEnvironmentFlag++;
369 break;
371 case 't':
372 /* ignored for backwards compatibility */
373 break;
375 case 'u':
376 Py_UnbufferedStdioFlag = 1;
377 saw_unbuffered_flag = 1;
378 break;
380 case 'v':
381 Py_VerboseFlag++;
382 break;
384 case 'x':
385 skipfirstline = 1;
386 break;
388 /* case 'X': reserved for implementation-specific arguments */
390 case 'h':
391 case '?':
392 help++;
393 break;
395 case 'V':
396 version++;
397 break;
399 case 'W':
400 PySys_AddWarnOption(_PyOS_optarg);
401 break;
403 /* This space reserved for other options */
405 default:
406 return usage(2, argv[0]);
407 /*NOTREACHED*/
412 if (help)
413 return usage(0, argv[0]);
415 if (version) {
416 fprintf(stderr, "Python %s\n", PY_VERSION);
417 return 0;
420 if (!Py_InspectFlag &&
421 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
422 Py_InspectFlag = 1;
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)
434 #ifdef __VMS
435 filename = decc$translate_vms(argv[_PyOS_optind]);
436 if (filename == (char *)0 || filename == (char *)-1)
437 filename = argv[_PyOS_optind];
439 #else
440 filename = argv[_PyOS_optind];
441 #endif
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);
450 #endif
451 #ifdef HAVE_SETVBUF
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) {
462 #ifdef MS_WINDOWS
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 */
467 #ifdef HAVE_SETVBUF
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. */
474 #ifdef __VMS
475 else {
476 setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
478 #endif /* __VMS */
480 #ifdef __APPLE__
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
489 script. */
490 if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') {
491 wchar_t* buffer;
492 size_t len = strlen(p);
493 size_t r;
495 buffer = malloc(len * sizeof(wchar_t));
496 if (buffer == NULL) {
497 Py_FatalError(
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 */
504 } else {
505 Py_SetProgramName(argv[0]);
507 #else
508 Py_SetProgramName(argv[0]);
509 #endif
510 Py_Initialize();
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());
516 if (!Py_NoSiteFlag)
517 fprintf(stderr, "%s\n", COPYRIGHT);
520 if (command != NULL) {
521 /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
522 _PyOS_optind--;
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 ''*/
529 _PyOS_optind--;
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))) {
537 PyObject *v;
538 v = PyImport_ImportModule("readline");
539 if (v == NULL)
540 PyErr_Clear();
541 else
542 Py_DECREF(v);
545 if (command) {
546 PyObject *commandObj = PyUnicode_FromWideChar(
547 command, wcslen(command));
548 free(command);
549 if (commandObj != NULL) {
550 sts = PyRun_SimpleStringFlags(
551 _PyUnicode_AsString(commandObj), &cf) != 0;
553 else {
554 PyErr_Print();
555 sts = 1;
557 Py_DECREF(commandObj);
558 } else if (module) {
559 sts = RunModule(module, 1);
561 else {
563 if (filename == NULL && stdin_is_interactive) {
564 Py_InspectFlag = 0; /* do exit on SystemExit */
565 RunStartupFile(&cf);
567 /* XXX */
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);
579 if (r == 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));
589 return 2;
591 else if (skipfirstline) {
592 int ch;
593 /* Push back first newline so line numbers
594 remain the same */
595 while ((ch = getc(fp)) != EOF) {
596 if (ch == '\n') {
597 (void)ungetc(ch, fp);
598 break;
603 /* XXX: does this work on Win/Win64? (see posix_fstat) */
604 struct stat sb;
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);
608 fclose(fp);
609 return 1;
614 if (sts==-1) {
615 PyObject *filenameObj = NULL;
616 char *p_cfilename = "<stdin>";
617 if (filename) {
618 filenameObj = PyUnicode_FromWideChar(
619 filename, wcslen(filename));
620 if (filenameObj != NULL)
621 p_cfilename = _PyUnicode_AsString(filenameObj);
622 else
623 p_cfilename = "<decoding error>";
625 sts = PyRun_AnyFileExFlags(
627 p_cfilename,
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')
640 Py_InspectFlag = 1;
643 if (Py_InspectFlag && stdin_is_interactive &&
644 (filename != NULL || command != NULL || module != NULL)) {
645 Py_InspectFlag = 0;
646 /* XXX */
647 sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
650 WaitForThreadShutdown();
652 Py_Finalize();
654 #ifdef __INSURE__
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
662 * reports. -baw
664 _Py_ReleaseInternedStrings();
665 _Py_ReleaseInternedUnicodeStrings();
666 #endif /* __INSURE__ */
668 return sts;
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. */
678 void
679 Py_GetArgcArgv(int *argc, wchar_t ***argv)
681 *argc = orig_argc;
682 *argv = orig_argv;
685 #ifdef __cplusplus
687 #endif