Updated documentation for findCaller() to indicate that a 3-tuple is now returned...
[python.git] / Modules / main.c
blob2224dfe2f0486c73e12bb93cf364886bc4e9085f
1 /* Python interpreter main program */
3 #include "Python.h"
4 #include "osdefs.h"
5 #include "code.h" /* For CO_FUTURE_DIVISION */
6 #include "import.h"
8 #ifdef __VMS
9 #include <unixlib.h>
10 #endif
12 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
13 #ifdef HAVE_FCNTL_H
14 #include <fcntl.h>
15 #endif
16 #endif
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
28 #include "pygetopt.h"
30 #define COPYRIGHT \
31 "Type \"help\", \"copyright\", \"credits\" or \"license\" " \
32 "for more information."
34 #ifdef __cplusplus
35 extern "C" {
36 #endif
38 /* For Py_GetArgcArgv(); set by main() */
39 static char **orig_argv;
40 static int orig_argc;
42 /* command line options */
43 #define BASE_OPTS "c:dEhim:OQ:StuUvVW:xX?"
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*/
55 /* Short usage message (with %s for argv0) */
56 static char *usage_line =
57 "usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
59 /* Long usage message, split into parts < 512 bytes */
60 static char *usage_1 = "\
61 Options and arguments (and corresponding environment variables):\n\
62 -c cmd : program passed in as string (terminates option list)\n\
63 -d : debug output from parser; also PYTHONDEBUG=x\n\
64 -E : ignore environment variables (such as PYTHONPATH)\n\
65 -h : print this help message and exit (also --help)\n\
66 -i : inspect interactively after running script; forces a prompt even\n\
67 if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n\
69 static char *usage_2 = "\
70 -m mod : run library module as a script (terminates option list)\n\
71 -O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x\n\
72 -OO : remove doc-strings in addition to the -O optimizations\n\
73 -Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew\n\
74 -S : don't imply 'import site' on initialization\n\
75 -t : issue warnings about inconsistent tab usage (-tt: issue errors)\n\
76 -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x\n\
78 static char *usage_3 = "\
79 see man page for details on internal buffering relating to '-u'\n\
80 -v : verbose (trace import statements); also PYTHONVERBOSE=x\n\
81 can be supplied multiple times to increase verbosity\n\
82 -V : print the Python version number and exit (also --version)\n\
83 -W arg : warning control; arg is action:message:category:module:lineno\n\
84 -x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
85 file : program read from script file\n\
86 - : program read from stdin (default; interactive mode if a tty)\n\
88 static char *usage_4 = "\
89 arg ...: arguments passed to program in sys.argv[1:]\n\n\
90 Other environment variables:\n\
91 PYTHONSTARTUP: file executed on interactive startup (no default)\n\
92 PYTHONPATH : '%c'-separated list of directories prefixed to the\n\
93 default module search path. The result is sys.path.\n\
94 PYTHONHOME : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
95 The default module search path uses %s.\n\
96 PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
100 static int
101 usage(int exitcode, char* program)
103 FILE *f = exitcode ? stderr : stdout;
105 fprintf(f, usage_line, program);
106 if (exitcode)
107 fprintf(f, "Try `python -h' for more information.\n");
108 else {
109 fprintf(f, usage_1);
110 fprintf(f, usage_2);
111 fprintf(f, usage_3);
112 fprintf(f, usage_4, DELIM, DELIM, PYTHONHOMEHELP);
114 #if defined(__VMS)
115 if (exitcode == 0) {
116 /* suppress 'error' message */
117 return 1;
119 else {
120 /* STS$M_INHIB_MSG + SS$_ABORT */
121 return 0x1000002c;
123 #else
124 return exitcode;
125 #endif
126 /*NOTREACHED*/
129 static void RunStartupFile(PyCompilerFlags *cf)
131 char *startup = Py_GETENV("PYTHONSTARTUP");
132 if (startup != NULL && startup[0] != '\0') {
133 FILE *fp = fopen(startup, "r");
134 if (fp != NULL) {
135 (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
136 PyErr_Clear();
137 fclose(fp);
143 static int RunModule(char *module)
145 PyObject *runpy, *runmodule, *runargs, *result;
146 runpy = PyImport_ImportModule("runpy");
147 if (runpy == NULL) {
148 fprintf(stderr, "Could not import runpy module\n");
149 return -1;
151 runmodule = PyObject_GetAttrString(runpy, "run_module");
152 if (runmodule == NULL) {
153 fprintf(stderr, "Could not access runpy.run_module\n");
154 Py_DECREF(runpy);
155 return -1;
157 runargs = Py_BuildValue("sOsO", module,
158 Py_None, "__main__", Py_True);
159 if (runargs == NULL) {
160 fprintf(stderr,
161 "Could not create arguments for runpy.run_module\n");
162 Py_DECREF(runpy);
163 Py_DECREF(runmodule);
164 return -1;
166 result = PyObject_Call(runmodule, runargs, NULL);
167 if (result == NULL) {
168 PyErr_Print();
170 Py_DECREF(runpy);
171 Py_DECREF(runmodule);
172 Py_DECREF(runargs);
173 if (result == NULL) {
174 return -1;
176 Py_DECREF(result);
177 return 0;
180 /* Main program */
183 Py_Main(int argc, char **argv)
185 int c;
186 int sts;
187 char *command = NULL;
188 char *filename = NULL;
189 char *module = NULL;
190 FILE *fp = stdin;
191 char *p;
192 int inspect = 0;
193 int unbuffered = 0;
194 int skipfirstline = 0;
195 int stdin_is_interactive = 0;
196 int help = 0;
197 int version = 0;
198 int saw_inspect_flag = 0;
199 int saw_unbuffered_flag = 0;
200 PyCompilerFlags cf;
202 cf.cf_flags = 0;
204 orig_argc = argc; /* For Py_GetArgcArgv() */
205 orig_argv = argv;
207 #ifdef RISCOS
208 Py_RISCOSWimpFlag = 0;
209 #endif
211 PySys_ResetWarnOptions();
213 while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
214 if (c == 'c') {
215 /* -c is the last option; following arguments
216 that look like options are left for the
217 command to interpret. */
218 command = (char *)malloc(strlen(_PyOS_optarg) + 2);
219 if (command == NULL)
220 Py_FatalError(
221 "not enough memory to copy -c argument");
222 strcpy(command, _PyOS_optarg);
223 strcat(command, "\n");
224 break;
227 if (c == 'm') {
228 /* -m is the last option; following arguments
229 that look like options are left for the
230 module to interpret. */
231 module = (char *)malloc(strlen(_PyOS_optarg) + 2);
232 if (module == NULL)
233 Py_FatalError(
234 "not enough memory to copy -m argument");
235 strcpy(module, _PyOS_optarg);
236 break;
239 switch (c) {
241 case 'd':
242 Py_DebugFlag++;
243 break;
245 case 'Q':
246 if (strcmp(_PyOS_optarg, "old") == 0) {
247 Py_DivisionWarningFlag = 0;
248 break;
250 if (strcmp(_PyOS_optarg, "warn") == 0) {
251 Py_DivisionWarningFlag = 1;
252 break;
254 if (strcmp(_PyOS_optarg, "warnall") == 0) {
255 Py_DivisionWarningFlag = 2;
256 break;
258 if (strcmp(_PyOS_optarg, "new") == 0) {
259 /* This only affects __main__ */
260 cf.cf_flags |= CO_FUTURE_DIVISION;
261 /* And this tells the eval loop to treat
262 BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
263 _Py_QnewFlag = 1;
264 break;
266 fprintf(stderr,
267 "-Q option should be `-Qold', "
268 "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
269 return usage(2, argv[0]);
270 /* NOTREACHED */
272 case 'i':
273 inspect++;
274 saw_inspect_flag = 1;
275 Py_InteractiveFlag++;
276 break;
278 case 'O':
279 Py_OptimizeFlag++;
280 break;
282 case 'S':
283 Py_NoSiteFlag++;
284 break;
286 case 'E':
287 Py_IgnoreEnvironmentFlag++;
288 break;
290 case 't':
291 Py_TabcheckFlag++;
292 break;
294 case 'u':
295 unbuffered++;
296 saw_unbuffered_flag = 1;
297 break;
299 case 'v':
300 Py_VerboseFlag++;
301 break;
303 #ifdef RISCOS
304 case 'w':
305 Py_RISCOSWimpFlag = 1;
306 break;
307 #endif
309 case 'x':
310 skipfirstline = 1;
311 break;
313 case 'U':
314 Py_UnicodeFlag++;
315 break;
316 case 'h':
317 case '?':
318 help++;
319 break;
320 case 'V':
321 version++;
322 break;
324 case 'W':
325 PySys_AddWarnOption(_PyOS_optarg);
326 break;
328 /* This space reserved for other options */
330 default:
331 return usage(2, argv[0]);
332 /*NOTREACHED*/
337 if (help)
338 return usage(0, argv[0]);
340 if (version) {
341 fprintf(stderr, "Python %s\n", PY_VERSION);
342 return 0;
345 if (!saw_inspect_flag &&
346 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
347 inspect = 1;
348 if (!saw_unbuffered_flag &&
349 (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
350 unbuffered = 1;
352 if (command == NULL && module == NULL && _PyOS_optind < argc &&
353 strcmp(argv[_PyOS_optind], "-") != 0)
355 #ifdef __VMS
356 filename = decc$translate_vms(argv[_PyOS_optind]);
357 if (filename == (char *)0 || filename == (char *)-1)
358 filename = argv[_PyOS_optind];
360 #else
361 filename = argv[_PyOS_optind];
362 #endif
363 if (filename != NULL) {
364 if ((fp = fopen(filename, "r")) == NULL) {
365 #ifdef HAVE_STRERROR
366 fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
367 argv[0], filename, errno, strerror(errno));
368 #else
369 fprintf(stderr, "%s: can't open file '%s': Errno %d\n",
370 argv[0], filename, errno);
371 #endif
372 return 2;
374 else if (skipfirstline) {
375 int ch;
376 /* Push back first newline so line numbers
377 remain the same */
378 while ((ch = getc(fp)) != EOF) {
379 if (ch == '\n') {
380 (void)ungetc(ch, fp);
381 break;
386 /* XXX: does this work on Win/Win64? (see posix_fstat) */
387 struct stat sb;
388 if (fstat(fileno(fp), &sb) == 0 &&
389 S_ISDIR(sb.st_mode)) {
390 fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);
391 return 1;
397 stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
399 if (unbuffered) {
400 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
401 _setmode(fileno(stdin), O_BINARY);
402 _setmode(fileno(stdout), O_BINARY);
403 #endif
404 #ifdef HAVE_SETVBUF
405 setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
406 setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
407 setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
408 #else /* !HAVE_SETVBUF */
409 setbuf(stdin, (char *)NULL);
410 setbuf(stdout, (char *)NULL);
411 setbuf(stderr, (char *)NULL);
412 #endif /* !HAVE_SETVBUF */
414 else if (Py_InteractiveFlag) {
415 #ifdef MS_WINDOWS
416 /* Doesn't have to have line-buffered -- use unbuffered */
417 /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
418 setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
419 #else /* !MS_WINDOWS */
420 #ifdef HAVE_SETVBUF
421 setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
422 setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
423 #endif /* HAVE_SETVBUF */
424 #endif /* !MS_WINDOWS */
425 /* Leave stderr alone - it should be unbuffered anyway. */
427 #ifdef __VMS
428 else {
429 setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
431 #endif /* __VMS */
433 #ifdef __APPLE__
434 /* On MacOS X, when the Python interpreter is embedded in an
435 application bundle, it gets executed by a bootstrapping script
436 that does os.execve() with an argv[0] that's different from the
437 actual Python executable. This is needed to keep the Finder happy,
438 or rather, to work around Apple's overly strict requirements of
439 the process name. However, we still need a usable sys.executable,
440 so the actual executable path is passed in an environment variable.
441 See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
442 script. */
443 if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')
444 Py_SetProgramName(p);
445 else
446 Py_SetProgramName(argv[0]);
447 #else
448 Py_SetProgramName(argv[0]);
449 #endif
450 Py_Initialize();
452 if (Py_VerboseFlag ||
453 (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
454 fprintf(stderr, "Python %s on %s\n",
455 Py_GetVersion(), Py_GetPlatform());
456 if (!Py_NoSiteFlag)
457 fprintf(stderr, "%s\n", COPYRIGHT);
460 if (command != NULL) {
461 /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
462 _PyOS_optind--;
463 argv[_PyOS_optind] = "-c";
466 if (module != NULL) {
467 /* Backup _PyOS_optind and force sys.argv[0] = '-c'
468 so that PySys_SetArgv correctly sets sys.path[0] to ''*/
469 _PyOS_optind--;
470 argv[_PyOS_optind] = "-c";
473 PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
475 if ((inspect || (command == NULL && filename == NULL && module == NULL)) &&
476 isatty(fileno(stdin))) {
477 PyObject *v;
478 v = PyImport_ImportModule("readline");
479 if (v == NULL)
480 PyErr_Clear();
481 else
482 Py_DECREF(v);
485 if (command) {
486 sts = PyRun_SimpleStringFlags(command, &cf) != 0;
487 free(command);
488 } else if (module) {
489 sts = RunModule(module);
490 free(module);
492 else {
493 if (filename == NULL && stdin_is_interactive) {
494 RunStartupFile(&cf);
496 /* XXX */
497 sts = PyRun_AnyFileExFlags(
499 filename == NULL ? "<stdin>" : filename,
500 filename != NULL, &cf) != 0;
503 /* Check this environment variable at the end, to give programs the
504 * opportunity to set it from Python.
506 if (!saw_inspect_flag &&
507 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
509 inspect = 1;
512 if (inspect && stdin_is_interactive &&
513 (filename != NULL || command != NULL || module != NULL))
514 /* XXX */
515 sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
517 Py_Finalize();
518 #ifdef RISCOS
519 if (Py_RISCOSWimpFlag)
520 fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
521 #endif
523 #ifdef __INSURE__
524 /* Insure++ is a memory analysis tool that aids in discovering
525 * memory leaks and other memory problems. On Python exit, the
526 * interned string dictionary is flagged as being in use at exit
527 * (which it is). Under normal circumstances, this is fine because
528 * the memory will be automatically reclaimed by the system. Under
529 * memory debugging, it's a huge source of useless noise, so we
530 * trade off slower shutdown for less distraction in the memory
531 * reports. -baw
533 _Py_ReleaseInternedStrings();
534 #endif /* __INSURE__ */
536 return sts;
539 /* this is gonna seem *real weird*, but if you put some other code between
540 Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
541 while statement in Misc/gdbinit:ppystack */
543 /* Make the *original* argc/argv available to other modules.
544 This is rare, but it is needed by the secureware extension. */
546 void
547 Py_GetArgcArgv(int *argc, char ***argv)
549 *argc = orig_argc;
550 *argv = orig_argv;
553 #ifdef __cplusplus
555 #endif