source: vendor/python/2.5/Modules/main.c

Last change on this file was 3225, checked in by bird, 18 years ago

Python 2.5

File size: 13.7 KB
Line 
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
35extern "C" {
36#endif
37
38/* For Py_GetArgcArgv(); set by main() */
39static char **orig_argv;
40static int orig_argc;
41
42/* command line options */
43#define BASE_OPTS "c:dEhim:OQ:StuUvVW: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 */
52extern int Py_RISCOSWimpFlag;
53#endif /*RISCOS*/
54
55/* Short usage message (with %s for argv0) */
56static char *usage_line =
57"usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
58
59/* Long usage message, split into parts < 512 bytes */
60static char *usage_1 = "\
61Options 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, (also PYTHONINSPECT=x)\n\
67 and force prompts, even if stdin does not appear to be a terminal\n\
68";
69static 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\
77";
78static 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 (also --version)\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\
84file : program read from script file\n\
85- : program read from stdin (default; interactive mode if a tty)\n\
86";
87static char *usage_4 = "\
88arg ...: arguments passed to program in sys.argv[1:]\n\
89Other environment variables:\n\
90PYTHONSTARTUP: file executed on interactive startup (no default)\n\
91PYTHONPATH : '%c'-separated list of directories prefixed to the\n\
92 default module search path. The result is sys.path.\n\
93PYTHONHOME : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
94 The default module search path uses %s.\n\
95PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
96";
97
98
99static int
100usage(int exitcode, char* program)
101{
102 FILE *f = exitcode ? stderr : stdout;
103
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);
112 }
113#if defined(__VMS)
114 if (exitcode == 0) {
115 /* suppress 'error' message */
116 return 1;
117 }
118 else {
119 /* STS$M_INHIB_MSG + SS$_ABORT */
120 return 0x1000002c;
121 }
122#else
123 return exitcode;
124#endif
125 /*NOTREACHED*/
126}
127
128static void RunStartupFile(PyCompilerFlags *cf)
129{
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);
137 }
138 }
139}
140
141
142static int RunModule(char *module)
143{
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;
149 }
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;
155 }
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;
164 }
165 result = PyObject_Call(runmodule, runargs, NULL);
166 if (result == NULL) {
167 PyErr_Print();
168 }
169 Py_DECREF(runpy);
170 Py_DECREF(runmodule);
171 Py_DECREF(runargs);
172 if (result == NULL) {
173 return -1;
174 }
175 Py_DECREF(result);
176 return 0;
177}
178
179/* Main program */
180
181int
182Py_Main(int argc, char **argv)
183{
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;
200
201 cf.cf_flags = 0;
202
203 orig_argc = argc; /* For Py_GetArgcArgv() */
204 orig_argv = argv;
205
206#ifdef RISCOS
207 Py_RISCOSWimpFlag = 0;
208#endif
209
210 PySys_ResetWarnOptions();
211
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;
224 }
225
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;
236 }
237
238 switch (c) {
239
240 case 'd':
241 Py_DebugFlag++;
242 break;
243
244 case 'Q':
245 if (strcmp(_PyOS_optarg, "old") == 0) {
246 Py_DivisionWarningFlag = 0;
247 break;
248 }
249 if (strcmp(_PyOS_optarg, "warn") == 0) {
250 Py_DivisionWarningFlag = 1;
251 break;
252 }
253 if (strcmp(_PyOS_optarg, "warnall") == 0) {
254 Py_DivisionWarningFlag = 2;
255 break;
256 }
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;
264 }
265 fprintf(stderr,
266 "-Q option should be `-Qold', "
267 "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
268 return usage(2, argv[0]);
269 /* NOTREACHED */
270
271 case 'i':
272 inspect++;
273 saw_inspect_flag = 1;
274 Py_InteractiveFlag++;
275 break;
276
277 case 'O':
278 Py_OptimizeFlag++;
279 break;
280
281 case 'S':
282 Py_NoSiteFlag++;
283 break;
284
285 case 'E':
286 Py_IgnoreEnvironmentFlag++;
287 break;
288
289 case 't':
290 Py_TabcheckFlag++;
291 break;
292
293 case 'u':
294 unbuffered++;
295 saw_unbuffered_flag = 1;
296 break;
297
298 case 'v':
299 Py_VerboseFlag++;
300 break;
301
302#ifdef RISCOS
303 case 'w':
304 Py_RISCOSWimpFlag = 1;
305 break;
306#endif
307
308 case 'x':
309 skipfirstline = 1;
310 break;
311
312 case 'U':
313 Py_UnicodeFlag++;
314 break;
315 case 'h':
316 case '?':
317 help++;
318 break;
319 case 'V':
320 version++;
321 break;
322
323 case 'W':
324 PySys_AddWarnOption(_PyOS_optarg);
325 break;
326
327 /* This space reserved for other options */
328
329 default:
330 return usage(2, argv[0]);
331 /*NOTREACHED*/
332
333 }
334 }
335
336 if (help)
337 return usage(0, argv[0]);
338
339 if (version) {
340 fprintf(stderr, "Python %s\n", PY_VERSION);
341 return 0;
342 }
343
344 if (!saw_inspect_flag &&
345 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
346 inspect = 1;
347 if (!saw_unbuffered_flag &&
348 (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
349 unbuffered = 1;
350
351 if (command == NULL && module == NULL && _PyOS_optind < argc &&
352 strcmp(argv[_PyOS_optind], "-") != 0)
353 {
354#ifdef __VMS
355 filename = decc$translate_vms(argv[_PyOS_optind]);
356 if (filename == (char *)0 || filename == (char *)-1)
357 filename = argv[_PyOS_optind];
358
359#else
360 filename = argv[_PyOS_optind];
361#endif
362 if (filename != NULL) {
363 if ((fp = fopen(filename, "r")) == NULL) {
364#ifdef HAVE_STRERROR
365 fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
366 argv[0], filename, errno, strerror(errno));
367#else
368 fprintf(stderr, "%s: can't open file '%s': Errno %d\n",
369 argv[0], filename, errno);
370#endif
371 return 2;
372 }
373 else if (skipfirstline) {
374 int ch;
375 /* Push back first newline so line numbers
376 remain the same */
377 while ((ch = getc(fp)) != EOF) {
378 if (ch == '\n') {
379 (void)ungetc(ch, fp);
380 break;
381 }
382 }
383 }
384 {
385 /* XXX: does this work on Win/Win64? (see posix_fstat) */
386 struct stat sb;
387 if (fstat(fileno(fp), &sb) == 0 &&
388 S_ISDIR(sb.st_mode)) {
389 fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);
390 return 1;
391 }
392 }
393 }
394 }
395
396 stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
397
398 if (unbuffered) {
399#if defined(MS_WINDOWS) || defined(__CYGWIN__)
400 _setmode(fileno(stdin), O_BINARY);
401 _setmode(fileno(stdout), O_BINARY);
402#endif
403#ifdef HAVE_SETVBUF
404 setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
405 setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
406 setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
407#else /* !HAVE_SETVBUF */
408 setbuf(stdin, (char *)NULL);
409 setbuf(stdout, (char *)NULL);
410 setbuf(stderr, (char *)NULL);
411#endif /* !HAVE_SETVBUF */
412 }
413 else if (Py_InteractiveFlag) {
414#ifdef MS_WINDOWS
415 /* Doesn't have to have line-buffered -- use unbuffered */
416 /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
417 setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
418#else /* !MS_WINDOWS */
419#ifdef HAVE_SETVBUF
420 setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
421 setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
422#endif /* HAVE_SETVBUF */
423#endif /* !MS_WINDOWS */
424 /* Leave stderr alone - it should be unbuffered anyway. */
425 }
426#ifdef __VMS
427 else {
428 setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
429 }
430#endif /* __VMS */
431
432#ifdef __APPLE__
433 /* On MacOS X, when the Python interpreter is embedded in an
434 application bundle, it gets executed by a bootstrapping script
435 that does os.execve() with an argv[0] that's different from the
436 actual Python executable. This is needed to keep the Finder happy,
437 or rather, to work around Apple's overly strict requirements of
438 the process name. However, we still need a usable sys.executable,
439 so the actual executable path is passed in an environment variable.
440 See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
441 script. */
442 if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')
443 Py_SetProgramName(p);
444 else
445 Py_SetProgramName(argv[0]);
446#else
447 Py_SetProgramName(argv[0]);
448#endif
449 Py_Initialize();
450
451 if (Py_VerboseFlag ||
452 (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
453 fprintf(stderr, "Python %s on %s\n",
454 Py_GetVersion(), Py_GetPlatform());
455 if (!Py_NoSiteFlag)
456 fprintf(stderr, "%s\n", COPYRIGHT);
457 }
458
459 if (command != NULL) {
460 /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
461 _PyOS_optind--;
462 argv[_PyOS_optind] = "-c";
463 }
464
465 if (module != NULL) {
466 /* Backup _PyOS_optind and force sys.argv[0] = '-c'
467 so that PySys_SetArgv correctly sets sys.path[0] to ''*/
468 _PyOS_optind--;
469 argv[_PyOS_optind] = "-c";
470 }
471
472 PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
473
474 if ((inspect || (command == NULL && filename == NULL && module == NULL)) &&
475 isatty(fileno(stdin))) {
476 PyObject *v;
477 v = PyImport_ImportModule("readline");
478 if (v == NULL)
479 PyErr_Clear();
480 else
481 Py_DECREF(v);
482 }
483
484 if (command) {
485 sts = PyRun_SimpleStringFlags(command, &cf) != 0;
486 free(command);
487 } else if (module) {
488 sts = RunModule(module);
489 free(module);
490 }
491 else {
492 if (filename == NULL && stdin_is_interactive) {
493 RunStartupFile(&cf);
494 }
495 /* XXX */
496 sts = PyRun_AnyFileExFlags(
497 fp,
498 filename == NULL ? "<stdin>" : filename,
499 filename != NULL, &cf) != 0;
500 }
501
502 /* Check this environment variable at the end, to give programs the
503 * opportunity to set it from Python.
504 */
505 if (!saw_inspect_flag &&
506 (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
507 {
508 inspect = 1;
509 }
510
511 if (inspect && stdin_is_interactive &&
512 (filename != NULL || command != NULL || module != NULL))
513 /* XXX */
514 sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
515
516 Py_Finalize();
517#ifdef RISCOS
518 if (Py_RISCOSWimpFlag)
519 fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
520#endif
521
522#ifdef __INSURE__
523 /* Insure++ is a memory analysis tool that aids in discovering
524 * memory leaks and other memory problems. On Python exit, the
525 * interned string dictionary is flagged as being in use at exit
526 * (which it is). Under normal circumstances, this is fine because
527 * the memory will be automatically reclaimed by the system. Under
528 * memory debugging, it's a huge source of useless noise, so we
529 * trade off slower shutdown for less distraction in the memory
530 * reports. -baw
531 */
532 _Py_ReleaseInternedStrings();
533#endif /* __INSURE__ */
534
535 return sts;
536}
537
538/* this is gonna seem *real weird*, but if you put some other code between
539 Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
540 while statement in Misc/gdbinit:ppystack */
541
542/* Make the *original* argc/argv available to other modules.
543 This is rare, but it is needed by the secureware extension. */
544
545void
546Py_GetArgcArgv(int *argc, char ***argv)
547{
548 *argc = orig_argc;
549 *argv = orig_argv;
550}
551
552#ifdef __cplusplus
553}
554#endif
555
Note: See TracBrowser for help on using the repository browser.