main.c 10.6 KB
Newer Older
Guido van Rossum's avatar
Guido van Rossum committed
1 2 3
/* Python interpreter main program */

#include "Python.h"
4
#include "osdefs.h"
5
#include "compile.h" /* For CO_FUTURE_DIVISION */
Guido van Rossum's avatar
Guido van Rossum committed
6

7
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
8 9 10
#include <fcntl.h>
#endif

11
#if (defined(PYOS_OS2) && !defined(PYCC_GCC)) || defined(MS_WINDOWS)
12 13
#define PYTHONHOMEHELP "<prefix>\\lib"
#else
14 15 16
#if defined(PYOS_OS2) && defined(PYCC_GCC)
#define PYTHONHOMEHELP "<prefix>/Lib"
#else
17
#define PYTHONHOMEHELP "<prefix>/pythonX.X"
18
#endif
19
#endif
20

21 22
#include "pygetopt.h"

23
#define COPYRIGHT \
24 25
    "Type \"help\", \"copyright\", \"credits\" or \"license\" " \
    "for more information."
26

27
/* For Py_GetArgcArgv(); set by main() */
Guido van Rossum's avatar
Guido van Rossum committed
28 29 30
static char **orig_argv;
static int  orig_argc;

31
/* command line options */
32
#define BASE_OPTS "c:dEhiOQ:StuUvVW:xX"
33 34 35 36 37 38 39 40

#ifndef RISCOS
#define PROGRAM_OPTS BASE_OPTS
#else /*RISCOS*/
/* extra option saying that we are running under a special task window
   frontend; especially my_readline will behave different */
#define PROGRAM_OPTS BASE_OPTS "w"
/* corresponding flag */
41
extern int Py_RISCOSWimpFlag;
42
#endif /*RISCOS*/
43

Guido van Rossum's avatar
Guido van Rossum committed
44 45
/* Short usage message (with %s for argv0) */
static char *usage_line =
46
"usage: %s [option] ... [-c cmd | file | -] [arg] ...\n";
Guido van Rossum's avatar
Guido van Rossum committed
47 48

/* Long usage message, split into parts < 512 bytes */
49
static char *usage_1 = "\
Guido van Rossum's avatar
Guido van Rossum committed
50
Options and arguments (and corresponding environment variables):\n\
51
-c cmd : program passed in as string (terminates option list)\n\
Guido van Rossum's avatar
Guido van Rossum committed
52
-d     : debug output from parser (also PYTHONDEBUG=x)\n\
53 54
-E     : ignore environment variables (such as PYTHONPATH)\n\
-h     : print this help message and exit\n\
55
-i     : inspect interactively after running script, (also PYTHONINSPECT=x)\n\
56
         and force prompts, even if stdin does not appear to be a terminal\n\
57 58
";
static char *usage_2 = "\
59
-O     : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)\n\
60
-OO    : remove doc-strings in addition to the -O optimizations\n\
61
-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew\n\
62
-S     : don't imply 'import site' on initialization\n\
63 64
-t     : issue warnings about inconsistent tab usage (-tt: issue errors)\n\
-u     : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x)\n\
65
         see man page for details on internal buffering relating to '-u'\n\
66 67
";
static char *usage_3 = "\
Guido van Rossum's avatar
Guido van Rossum committed
68
-v     : verbose (trace import statements) (also PYTHONVERBOSE=x)\n\
69
-V     : print the Python version number and exit\n\
Guido van Rossum's avatar
Guido van Rossum committed
70
-W arg : warning control (arg is action:message:category:module:lineno)\n\
71
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
Guido van Rossum's avatar
Guido van Rossum committed
72 73
file   : program read from script file\n\
-      : program read from stdin (default; interactive mode if a tty)\n\
74
";
75
static char *usage_4 = "\
76
arg ...: arguments passed to program in sys.argv[1:]\n\
Guido van Rossum's avatar
Guido van Rossum committed
77 78
Other environment variables:\n\
PYTHONSTARTUP: file executed on interactive startup (no default)\n\
79
PYTHONPATH   : '%c'-separated list of directories prefixed to the\n\
Guido van Rossum's avatar
Guido van Rossum committed
80
               default module search path.  The result is sys.path.\n\
81 82
PYTHONHOME   : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
               The default module search path uses %s.\n\
83
PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
Guido van Rossum's avatar
Guido van Rossum committed
84 85 86
";


87 88 89
static void
usage(int exitcode, char* program)
{
90 91 92 93 94 95 96 97 98 99 100
	FILE *f = exitcode ? stderr : stdout;

	fprintf(f, usage_line, program);
	if (exitcode)
		fprintf(f, "Try `python -h' for more information.\n");
	else {
		fprintf(f, usage_1);
		fprintf(f, usage_2);
		fprintf(f, usage_3);
		fprintf(f, usage_4, DELIM, DELIM, PYTHONHOMEHELP);
	}
101 102 103 104 105
	exit(exitcode);
	/*NOTREACHED*/
}


Guido van Rossum's avatar
Guido van Rossum committed
106 107
/* Main program */

108
int
109
Py_Main(int argc, char **argv)
Guido van Rossum's avatar
Guido van Rossum committed
110 111 112 113 114 115 116 117 118
{
	int c;
	int sts;
	char *command = NULL;
	char *filename = NULL;
	FILE *fp = stdin;
	char *p;
	int inspect = 0;
	int unbuffered = 0;
119
	int skipfirstline = 0;
120
	int stdin_is_interactive = 0;
121 122
	int help = 0;
	int version = 0;
123 124
	int saw_inspect_flag = 0;
	int saw_unbuffered_flag = 0;
125
	PyCompilerFlags cf;
Guido van Rossum's avatar
Guido van Rossum committed
126

127 128
	cf.cf_flags = 0;

129
	orig_argc = argc;	/* For Py_GetArgcArgv() */
Guido van Rossum's avatar
Guido van Rossum committed
130
	orig_argv = argv;
131

132 133 134 135
#ifdef RISCOS
	Py_RISCOSWimpFlag = 0;
#endif

Guido van Rossum's avatar
Guido van Rossum committed
136 137
	PySys_ResetWarnOptions();

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
#if defined(WITH_NEXT_FRAMEWORK)
	/* If we are running from a framework it could be that we are actually
	** the main program for an applet. If so, the next call will return the
	** filename that we are supposed to run.
	*/
	filename = PyMac_GetAppletScriptFile();
	if (filename != NULL) {
		if ((fp = fopen(filename, "r")) == NULL) {
			fprintf(stderr, "%s: can't open file '%s'\n",
				argv[0], filename);
			exit(2);
		}
	}
	/* Skip option-processing if we are an applet */
	if (filename == NULL)
#endif
154
	while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
Guido van Rossum's avatar
Guido van Rossum committed
155 156 157 158
		if (c == 'c') {
			/* -c is the last option; following arguments
			   that look like options are left for the
			   the command to interpret. */
159
			command = malloc(strlen(_PyOS_optarg) + 2);
Guido van Rossum's avatar
Guido van Rossum committed
160 161 162
			if (command == NULL)
				Py_FatalError(
				   "not enough memory to copy -c argument");
163
			strcpy(command, _PyOS_optarg);
Guido van Rossum's avatar
Guido van Rossum committed
164 165 166
			strcat(command, "\n");
			break;
		}
167

Guido van Rossum's avatar
Guido van Rossum committed
168 169 170 171 172 173
		switch (c) {

		case 'd':
			Py_DebugFlag++;
			break;

174
		case 'Q':
175 176 177 178 179
			if (strcmp(_PyOS_optarg, "old") == 0) {
				Py_DivisionWarningFlag = 0;
				break;
			}
			if (strcmp(_PyOS_optarg, "warn") == 0) {
180 181 182 183 184
				Py_DivisionWarningFlag = 1;
				break;
			}
			if (strcmp(_PyOS_optarg, "warnall") == 0) {
				Py_DivisionWarningFlag = 2;
185 186 187
				break;
			}
			if (strcmp(_PyOS_optarg, "new") == 0) {
188
				/* This only affects __main__ */
189
				cf.cf_flags |= CO_FUTURE_DIVISION;
190 191 192
				/* And this tells the eval loop to treat
				   BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
				_Py_QnewFlag = 1;
193 194 195
				break;
			}
			fprintf(stderr,
196 197
				"-Q option should be `-Qold', "
				"`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
198 199 200
			usage(2, argv[0]);
			/* NOTREACHED */

Guido van Rossum's avatar
Guido van Rossum committed
201 202
		case 'i':
			inspect++;
203
			saw_inspect_flag = 1;
204
			Py_InteractiveFlag++;
Guido van Rossum's avatar
Guido van Rossum committed
205 206
			break;

207 208 209 210
		case 'O':
			Py_OptimizeFlag++;
			break;

211 212 213 214
		case 'S':
			Py_NoSiteFlag++;
			break;

215 216 217 218
		case 'E':
			Py_IgnoreEnvironmentFlag++;
			break;

219 220 221 222
		case 't':
			Py_TabcheckFlag++;
			break;

Guido van Rossum's avatar
Guido van Rossum committed
223 224
		case 'u':
			unbuffered++;
225
			saw_unbuffered_flag = 1;
Guido van Rossum's avatar
Guido van Rossum committed
226 227 228 229 230 231
			break;

		case 'v':
			Py_VerboseFlag++;
			break;

232 233 234 235 236 237
#ifdef RISCOS
		case 'w':
			Py_RISCOSWimpFlag = 1;
			break;
#endif

238 239 240 241
		case 'x':
			skipfirstline = 1;
			break;

Guido van Rossum's avatar
Guido van Rossum committed
242 243 244
		case 'U':
			Py_UnicodeFlag++;
			break;
245 246 247 248 249 250
		case 'h':
			help++;
			break;
		case 'V':
			version++;
			break;
Guido van Rossum's avatar
Guido van Rossum committed
251

Guido van Rossum's avatar
Guido van Rossum committed
252 253 254 255
		case 'W':
			PySys_AddWarnOption(_PyOS_optarg);
			break;

Guido van Rossum's avatar
Guido van Rossum committed
256 257 258
		/* This space reserved for other options */

		default:
259
			usage(2, argv[0]);
Guido van Rossum's avatar
Guido van Rossum committed
260 261 262 263 264
			/*NOTREACHED*/

		}
	}

265 266 267 268 269 270 271 272
	if (help)
		usage(0, argv[0]);

	if (version) {
		fprintf(stderr, "Python %s\n", PY_VERSION);
		exit(0);
	}

273 274 275 276 277 278 279
	if (!saw_inspect_flag &&
	    (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
		inspect = 1;
	if (!saw_unbuffered_flag &&
	    (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
		unbuffered = 1;

280
	if (command == NULL && filename == NULL && _PyOS_optind < argc &&
281
	    strcmp(argv[_PyOS_optind], "-") != 0)
282
	{
283
		filename = argv[_PyOS_optind];
284 285 286 287 288 289
		if (filename != NULL) {
			if ((fp = fopen(filename, "r")) == NULL) {
				fprintf(stderr, "%s: can't open file '%s'\n",
					argv[0], filename);
				exit(2);
			}
290
			else if (skipfirstline) {
291 292 293 294 295 296 297 298 299
				int ch;
				/* Push back first newline so line numbers
				   remain the same */
				while ((ch = getc(fp)) != EOF) {
					if (ch == '\n') {
						(void)ungetc(ch, fp);
						break;
					}
				}
300
			}
301 302 303 304 305
		}
	}

	stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);

Guido van Rossum's avatar
Guido van Rossum committed
306
	if (unbuffered) {
307
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
308 309
		_setmode(fileno(stdin), O_BINARY);
		_setmode(fileno(stdout), O_BINARY);
310
#endif
Guido van Rossum's avatar
Guido van Rossum committed
311
#ifndef MPW
312
#ifdef HAVE_SETVBUF
313 314 315
		setvbuf(stdin,  (char *)NULL, _IONBF, BUFSIZ);
		setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
		setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
316 317 318 319 320 321
#else /* !HAVE_SETVBUF */
		setbuf(stdin,  (char *)NULL);
		setbuf(stdout, (char *)NULL);
		setbuf(stderr, (char *)NULL);
#endif /* !HAVE_SETVBUF */
#else /* MPW */
Guido van Rossum's avatar
Guido van Rossum committed
322
		/* On MPW (3.2) unbuffered seems to hang */
323
		setvbuf(stdin,  (char *)NULL, _IOLBF, BUFSIZ);
Guido van Rossum's avatar
Guido van Rossum committed
324 325
		setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
		setvbuf(stderr, (char *)NULL, _IOLBF, BUFSIZ);
326
#endif /* MPW */
Guido van Rossum's avatar
Guido van Rossum committed
327
	}
328
	else if (Py_InteractiveFlag) {
329 330
#ifdef MS_WINDOWS
		/* Doesn't have to have line-buffered -- use unbuffered */
331
		/* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
332
		setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
333 334
#else /* !MS_WINDOWS */
#ifdef HAVE_SETVBUF
335 336
		setvbuf(stdin,  (char *)NULL, _IOLBF, BUFSIZ);
		setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
337 338
#endif /* HAVE_SETVBUF */
#endif /* !MS_WINDOWS */
339 340
		/* Leave stderr alone - it should be unbuffered anyway. */
  	}
Guido van Rossum's avatar
Guido van Rossum committed
341

342 343 344
	Py_SetProgramName(argv[0]);
	Py_Initialize();

Guido van Rossum's avatar
Guido van Rossum committed
345
	if (Py_VerboseFlag ||
346
	    (command == NULL && filename == NULL && stdin_is_interactive))
347
		fprintf(stderr, "Python %s on %s\n%s\n",
348
			Py_GetVersion(), Py_GetPlatform(), COPYRIGHT);
349

Guido van Rossum's avatar
Guido van Rossum committed
350
	if (command != NULL) {
351 352 353
		/* Backup _PyOS_optind and force sys.argv[0] = '-c' */
		_PyOS_optind--;
		argv[_PyOS_optind] = "-c";
Guido van Rossum's avatar
Guido van Rossum committed
354 355
	}

356
	PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
Guido van Rossum's avatar
Guido van Rossum committed
357

358 359 360 361 362 363 364 365 366 367
	if ((inspect || (command == NULL && filename == NULL)) &&
	    isatty(fileno(stdin))) {
		PyObject *v;
		v = PyImport_ImportModule("readline");
		if (v == NULL)
			PyErr_Clear();
		else
			Py_DECREF(v);
	}

Guido van Rossum's avatar
Guido van Rossum committed
368
	if (command) {
369
		sts = PyRun_SimpleStringFlags(command, &cf) != 0;
370
		free(command);
Guido van Rossum's avatar
Guido van Rossum committed
371 372
	}
	else {
373
		if (filename == NULL && stdin_is_interactive) {
374
			char *startup = Py_GETENV("PYTHONSTARTUP");
Guido van Rossum's avatar
Guido van Rossum committed
375 376 377 378 379 380 381 382 383
			if (startup != NULL && startup[0] != '\0') {
				FILE *fp = fopen(startup, "r");
				if (fp != NULL) {
					(void) PyRun_SimpleFile(fp, startup);
					PyErr_Clear();
					fclose(fp);
				}
			}
		}
384 385
		/* XXX */
		sts = PyRun_AnyFileExFlags(
386
			fp,
387
			filename == NULL ? "<stdin>" : filename,
388
			filename != NULL, &cf) != 0;
Guido van Rossum's avatar
Guido van Rossum committed
389 390
	}

391
	if (inspect && stdin_is_interactive &&
Guido van Rossum's avatar
Guido van Rossum committed
392
	    (filename != NULL || command != NULL))
393 394
		/* XXX */
		sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
Guido van Rossum's avatar
Guido van Rossum committed
395

396
	Py_Finalize();
397
#ifdef RISCOS
398
	if (Py_RISCOSWimpFlag)
399 400
                fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
#endif
401 402 403 404 405 406 407 408 409 410 411 412 413 414

#ifdef __INSURE__
	/* Insure++ is a memory analysis tool that aids in discovering
	 * memory leaks and other memory problems.  On Python exit, the
	 * interned string dictionary is flagged as being in use at exit
	 * (which it is).  Under normal circumstances, this is fine because
	 * the memory will be automatically reclaimed by the system.  Under
	 * memory debugging, it's a huge source of useless noise, so we
	 * trade off slower shutdown for less distraction in the memory
	 * reports.  -baw
	 */
	_Py_ReleaseInternedStrings();
#endif /* __INSURE__ */

415
	return sts;
Guido van Rossum's avatar
Guido van Rossum committed
416 417 418 419 420 421 422
}


/* Make the *original* argc/argv available to other modules.
   This is rare, but it is needed by the secureware extension. */

void
423
Py_GetArgcArgv(int *argc, char ***argv)
Guido van Rossum's avatar
Guido van Rossum committed
424 425 426 427
{
	*argc = orig_argc;
	*argv = orig_argv;
}