Instead of doing a make test, run the regression tests out of the installed
[python.git] / Modules / main.c
blob0beea737405001a914b13bab4c354b44658731e5
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\n\
66 -i : inspect interactively after running script, (also PYTHONINSPECT=x)\n\
67 and force prompts, even if stdin does not appear to be a terminal\n\
69 static char *usage_2 = "\
70 -m mod : run library module as a script (terminates option list)\n\
71 -O : optimize generated bytecode (a tad; 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 -V : print the Python version number and exit\n\
82 -W arg : warning control (arg is action:message:category:module:lineno)\n\
83 -x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
84 file : program read from script file\n\
85 - : program read from stdin (default; interactive mode if a tty)\n\
87 static char *usage_4 = "\
88 arg ...: arguments passed to program in sys.argv[1:]\n\
89 Other environment variables:\n\
90 PYTHONSTARTUP: file executed on interactive startup (no default)\n\
91 PYTHONPATH : '%c'-separated list of directories prefixed to the\n\
92 default module search path. The result is sys.path.\n\
93 PYTHONHOME : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
94 The default module search path uses %s.\n\
95 PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
99 static int
100 usage(int exitcode, char* program)
102 FILE *f = exitcode ? stderr : stdout;
104 fprintf(f, usage_line, program);
105 if (exitcode)
106 fprintf(f, "Try `python -h' for more information.\n");
107 else {
108 fprintf(f, usage_1);
109 fprintf(f, usage_2);
110 fprintf(f, usage_3);
111 fprintf(f, usage_4, DELIM, DELIM, PYTHONHOMEHELP);
113 #if defined(__VMS)
114 if (exitcode == 0) {
115 /* suppress 'error' message */
116 return 1;
118 else {
119 /* STS$M_INHIB_MSG + SS$_ABORT */
120 return 0x1000002c;
122 #else
123 return exitcode;
124 #endif
125 /*NOTREACHED*/
128 static void RunStartupFile(PyCompilerFlags *cf)
130 char *startup = Py_GETENV("PYTHONSTARTUP");
131 if (startup != NULL && startup[0] != '\0') {
132 FILE *fp = fopen(startup, "r");
133 if (fp != NULL) {
134 (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
135 PyErr_Clear();
136 fclose(fp);
142 static int RunModule(char *module)
144 PyObject *runpy, *runmodule, *runargs, *result;
145 runpy = PyImport_ImportModule("runpy");
146 if (runpy == NULL) {
147 fprintf(stderr, "Could not import runpy module\n");
148 return -1;
150 runmodule = PyObject_GetAttrString(runpy, "run_module");
151 if (runmodule == NULL) {
152 fprintf(stderr, "Could not access runpy.run_module\n");
153 Py_DECREF(runpy);
154 return -1;
156 runargs = Py_BuildValue("sOsO", module,
157 Py_None, "__main__", Py_True);
158 if (runargs == NULL) {
159 fprintf(stderr,
160 "Could not create arguments for runpy.run_module\n");
161 Py_DECREF(runpy);
162 Py_DECREF(runmodule);
163 return -1;
165 result = PyObject_Call(runmodule, runargs, NULL);
166 if (result == NULL) {
167 PyErr_Print();
169 Py_DECREF(runpy);
170 Py_DECREF(runmodule);
171 Py_DECREF(runargs);
172 if (result == NULL) {
173 return -1;
175 Py_DECREF(result);
176 return 0;
179 /* Main program */
182 Py_Main(int argc, char **argv)
184 int c;
185 int sts;
186 char *command = NULL;
187 char *filename = NULL;
188 char *module = NULL;
189 FILE *fp = stdin;
190 char *p;
191 int inspect = 0;
192 int unbuffered = 0;
193 int skipfirstline = 0;
194 int stdin_is_interactive = 0;
195 int help = 0;
196 int version = 0;
197 int saw_inspect_flag = 0;
198 int saw_unbuffered_flag = 0;
199 PyCompilerFlags cf;
201 cf.cf_flags = 0;
203 orig_argc = argc; /* For Py_GetArgcArgv() */
204 orig_argv = argv;
206 #ifdef RISCOS
207 Py_RISCOSWimpFlag = 0;
208 #endif
210 PySys_ResetWarnOptions();
212 while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
213 if (c == 'c') {
214 /* -c is the last option; following arguments
215 that look like options are left for the
216 command to interpret. */
217 command = (char *)malloc(strlen(_PyOS_optarg) + 2);
218 if (command == NULL)
219 Py_FatalError(
220 "not enough memory to copy -c argument");
221 strcpy(command, _PyOS_optarg);
222 strcat(command, "\n");
223 break;
226 if (c == 'm') {
227 /* -m is the last option; following arguments
228 that look like options are left for the
229 module to interpret. */
230 module = (char *)malloc(strlen(_PyOS_optarg) + 2);
231 if (module == NULL)
232 Py_FatalError(
233 "not enough memory to copy -m argument");
234 strcpy(module, _PyOS_optarg);
235 break;
238 switch (c) {
240 case 'd':
241 Py_DebugFlag++;
242 break;
244 case 'Q':
245 if (strcmp(_PyOS_optarg, "old") == 0) {
246 Py_DivisionWarningFlag = 0;
247 break;
249 if (strcmp(_PyOS_optarg, "warn") == 0) {
250 Py_DivisionWarningFlag = 1;
251 break;
253 if (strcmp(_PyOS_optarg, "warnall") == 0) {
254 Py_DivisionWarningFlag = 2;
255 break;
257 if (strcmp(_PyOS_optarg, "new") == 0) {
258 /* This only affects __main__ */
259 cf.cf_flags |= CO_FUTURE_DIVISION;
260 /* And this tells the eval loop to treat
261 BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
262 _Py_QnewFlag = 1;
263 break;
265 fprintf(stderr,
266 "-Q option should be `-Qold', "
267 "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
268 return usage(2, argv[0]);
269 /* NOTREACHED */
271 case 'i':
272 inspect++;
273 saw_inspect_flag = 1;
274 Py_InteractiveFlag++;
275 break;
277 case 'O':
278 Py_OptimizeFlag++;
279 break;
281 case 'S':
282 Py_NoSiteFlag++;
283 break;
285 case 'E':
286 Py_IgnoreEnvironmentFlag++;
287 break;
289 case 't':
290 Py_TabcheckFlag++;
291 break;
293 case 'u':
294 unbuffered++;
295 saw_unbuffered_flag = 1;
296 break;
298 case 'v':
299 Py_VerboseFlag++;
300 break;
302 #ifdef RISCOS
303 case 'w':
304 Py_RISCOSWimpFlag = 1;
305 break;
306 #endif
308 case 'x':
309 skipfirstline = 1;
310 break;
312 case 'U':
313 Py_UnicodeFlag++;
314 break;
315 case 'h':
316 help++;
317 break;
318 case 'V':
319 version++;
320 break;
322 case 'W':
323 PySys_AddWarnOption(_PyOS_optarg);
324 break;
326 /* This space reserved for other options */
328 default:
329 return usage(2, argv[0]);
330 /*NOTREACHED*/
335 if (help)
336 return usage(0, argv[0]);
338 if (version) {
339 fprintf(stderr, "Python %s\n", PY_VERSION);
340 return 0;
343 if (!saw_inspect_flag &&
344 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
345 inspect = 1;
346 if (!saw_unbuffered_flag &&
347 (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
348 unbuffered = 1;
350 if (command == NULL && module == NULL && _PyOS_optind < argc &&
351 strcmp(argv[_PyOS_optind], "-") != 0)
353 #ifdef __VMS
354 filename = decc$translate_vms(argv[_PyOS_optind]);
355 if (filename == (char *)0 || filename == (char *)-1)
356 filename = argv[_PyOS_optind];
358 #else
359 filename = argv[_PyOS_optind];
360 #endif
361 if (filename != NULL) {
362 if ((fp = fopen(filename, "r")) == NULL) {
363 #ifdef HAVE_STRERROR
364 fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
365 argv[0], filename, errno, strerror(errno));
366 #else
367 fprintf(stderr, "%s: can't open file '%s': Errno %d\n",
368 argv[0], filename, errno);
369 #endif
370 return 2;
372 else if (skipfirstline) {
373 int ch;
374 /* Push back first newline so line numbers
375 remain the same */
376 while ((ch = getc(fp)) != EOF) {
377 if (ch == '\n') {
378 (void)ungetc(ch, fp);
379 break;
384 /* XXX: does this work on Win/Win64? (see posix_fstat) */
385 struct stat sb;
386 if (fstat(fileno(fp), &sb) == 0 &&
387 S_ISDIR(sb.st_mode)) {
388 fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);
389 return 1;
395 stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
397 if (unbuffered) {
398 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
399 _setmode(fileno(stdin), O_BINARY);
400 _setmode(fileno(stdout), O_BINARY);
401 #endif
402 #ifdef HAVE_SETVBUF
403 setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
404 setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
405 setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
406 #else /* !HAVE_SETVBUF */
407 setbuf(stdin, (char *)NULL);
408 setbuf(stdout, (char *)NULL);
409 setbuf(stderr, (char *)NULL);
410 #endif /* !HAVE_SETVBUF */
412 else if (Py_InteractiveFlag) {
413 #ifdef MS_WINDOWS
414 /* Doesn't have to have line-buffered -- use unbuffered */
415 /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
416 setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
417 #else /* !MS_WINDOWS */
418 #ifdef HAVE_SETVBUF
419 setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
420 setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
421 #endif /* HAVE_SETVBUF */
422 #endif /* !MS_WINDOWS */
423 /* Leave stderr alone - it should be unbuffered anyway. */
425 #ifdef __VMS
426 else {
427 setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
429 #endif /* __VMS */
431 #ifdef __APPLE__
432 /* On MacOS X, when the Python interpreter is embedded in an
433 application bundle, it gets executed by a bootstrapping script
434 that does os.execve() with an argv[0] that's different from the
435 actual Python executable. This is needed to keep the Finder happy,
436 or rather, to work around Apple's overly strict requirements of
437 the process name. However, we still need a usable sys.executable,
438 so the actual executable path is passed in an environment variable.
439 See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
440 script. */
441 if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')
442 Py_SetProgramName(p);
443 else
444 Py_SetProgramName(argv[0]);
445 #else
446 Py_SetProgramName(argv[0]);
447 #endif
448 Py_Initialize();
450 if (Py_VerboseFlag ||
451 (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
452 fprintf(stderr, "Python %s on %s\n",
453 Py_GetVersion(), Py_GetPlatform());
454 if (!Py_NoSiteFlag)
455 fprintf(stderr, "%s\n", COPYRIGHT);
458 if (command != NULL) {
459 /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
460 _PyOS_optind--;
461 argv[_PyOS_optind] = "-c";
464 if (module != NULL) {
465 /* Backup _PyOS_optind and force sys.argv[0] = '-c'
466 so that PySys_SetArgv correctly sets sys.path[0] to ''*/
467 _PyOS_optind--;
468 argv[_PyOS_optind] = "-c";
471 PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
473 if ((inspect || (command == NULL && filename == NULL && module == NULL)) &&
474 isatty(fileno(stdin))) {
475 PyObject *v;
476 v = PyImport_ImportModule("readline");
477 if (v == NULL)
478 PyErr_Clear();
479 else
480 Py_DECREF(v);
483 if (command) {
484 sts = PyRun_SimpleStringFlags(command, &cf) != 0;
485 free(command);
486 } else if (module) {
487 sts = RunModule(module);
488 free(module);
490 else {
491 if (filename == NULL && stdin_is_interactive) {
492 RunStartupFile(&cf);
494 /* XXX */
495 sts = PyRun_AnyFileExFlags(
497 filename == NULL ? "<stdin>" : filename,
498 filename != NULL, &cf) != 0;
501 /* Check this environment variable at the end, to give programs the
502 * opportunity to set it from Python.
504 if (!saw_inspect_flag &&
505 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
507 inspect = 1;
510 if (inspect && stdin_is_interactive &&
511 (filename != NULL || command != NULL || module != NULL))
512 /* XXX */
513 sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
515 Py_Finalize();
516 #ifdef RISCOS
517 if (Py_RISCOSWimpFlag)
518 fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
519 #endif
521 #ifdef __INSURE__
522 /* Insure++ is a memory analysis tool that aids in discovering
523 * memory leaks and other memory problems. On Python exit, the
524 * interned string dictionary is flagged as being in use at exit
525 * (which it is). Under normal circumstances, this is fine because
526 * the memory will be automatically reclaimed by the system. Under
527 * memory debugging, it's a huge source of useless noise, so we
528 * trade off slower shutdown for less distraction in the memory
529 * reports. -baw
531 _Py_ReleaseInternedStrings();
532 #endif /* __INSURE__ */
534 return sts;
537 /* this is gonna seem *real weird*, but if you put some other code between
538 Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
539 while statement in Misc/gdbinit:ppystack */
541 /* Make the *original* argc/argv available to other modules.
542 This is rare, but it is needed by the secureware extension. */
544 void
545 Py_GetArgcArgv(int *argc, char ***argv)
547 *argc = orig_argc;
548 *argv = orig_argv;
551 #ifdef __cplusplus
553 #endif