pythonrun.c revision ad6dfda9afa3459eb802618c07969f6a1a0a1287
1/***********************************************************
2Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3The Netherlands.
4
5                        All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Stichting Mathematisch
12Centrum or CWI or Corporation for National Research Initiatives or
13CNRI not be used in advertising or publicity pertaining to
14distribution of the software without specific, written prior
15permission.
16
17While CWI is the initial source for this software, a modified version
18is made available by the Corporation for National Research Initiatives
19(CNRI) at the Internet address ftp://ftp.python.org.
20
21STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28PERFORMANCE OF THIS SOFTWARE.
29
30******************************************************************/
31
32/* Python interpreter top-level routines, including init/exit */
33
34#include "Python.h"
35
36#include "grammar.h"
37#include "node.h"
38#include "parsetok.h"
39#undef argument /* Avoid conflict on Mac */
40#include "errcode.h"
41#include "compile.h"
42#include "eval.h"
43#include "marshal.h"
44
45#ifdef HAVE_UNISTD_H
46#include <unistd.h>
47#endif
48
49#ifdef HAVE_SIGNAL_H
50#include <signal.h>
51#endif
52
53#ifdef MS_WIN32
54#undef BYTE
55#undef arglist
56#include "windows.h"
57#endif
58
59extern char *Py_GetPath();
60
61extern grammar _PyParser_Grammar; /* From graminit.c */
62
63/* Forward */
64static void initmain Py_PROTO((void));
65static PyObject *run_err_node Py_PROTO((node *n, char *filename,
66				   PyObject *globals, PyObject *locals));
67static PyObject *run_node Py_PROTO((node *n, char *filename,
68			       PyObject *globals, PyObject *locals));
69static PyObject *run_pyc_file Py_PROTO((FILE *fp, char *filename,
70				   PyObject *globals, PyObject *locals));
71static void err_input Py_PROTO((perrdetail *));
72static void initsigs Py_PROTO((void));
73
74int Py_DebugFlag; /* Needed by parser.c */
75int Py_VerboseFlag; /* Needed by import.c */
76int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
77
78/* Initialize the current interpreter; pass in the Python path. */
79
80void
81Py_Setup()
82{
83	PyImport_Init();
84
85	/* Modules '__builtin__' and 'sys' are initialized here,
86	   they are needed by random bits of the interpreter.
87	   All other modules are optional and are initialized
88	   when they are first imported. */
89
90	PyBuiltin_Init(); /* Also initializes builtin exceptions */
91	PySys_Init();
92
93	PySys_SetPath(Py_GetPath());
94
95	initsigs(); /* Signal handling stuff, including initintr() */
96
97	initmain();
98}
99
100/* Create and interpreter and thread state and initialize them;
101   if we already have an interpreter and thread, do nothing.
102   Fatal error if the creation fails. */
103
104void
105Py_Initialize()
106{
107	PyThreadState *tstate;
108	PyInterpreterState *interp;
109	char *p;
110
111	if (PyThreadState_Get())
112		return;
113
114	if ((p = getenv("PYTHONDEBUG")) && *p != '\0')
115		Py_DebugFlag = 1;
116	if ((p = getenv("PYTHONVERBOSE")) && *p != '\0')
117		Py_VerboseFlag = 1;
118
119	interp = PyInterpreterState_New();
120	if (interp == NULL)
121		Py_FatalError("PyInterpreterState_New() failed");
122
123	tstate = PyThreadState_New(interp);
124	if (tstate == NULL)
125		Py_FatalError("PyThreadState_New() failed");
126	(void) PyThreadState_Swap(tstate);
127
128	Py_Setup();
129
130	PySys_SetPath(Py_GetPath());
131	/* XXX Who should set the path -- Setup or Initialize? */
132}
133
134static char *progname = "python";
135
136void
137Py_SetProgramName(pn)
138	char *pn;
139{
140	if (pn && *pn)
141		progname = pn;
142}
143
144char *
145Py_GetProgramName()
146{
147	return progname;
148}
149
150/*
151  Py_Initialize()
152  -- do everything, no-op on second call, call fatal on failure, set path
153
154  #2
155  -- create new interp+tstate & make it current, return NULL on failure,
156     make it current, do all setup, set path
157
158  #3
159  -- #2 without set path
160
161  #4
162  -- is there any point to #3 for caller-provided current interp+tstate?
163
164*/
165
166/* Create __main__ module */
167
168static void
169initmain()
170{
171	PyObject *m, *d;
172	m = PyImport_AddModule("__main__");
173	if (m == NULL)
174		Py_FatalError("can't create __main__ module");
175	d = PyModule_GetDict(m);
176	if (PyDict_GetItemString(d, "__builtins__") == NULL) {
177		if (PyDict_SetItemString(d, "__builtins__",
178					 PyEval_GetBuiltins()))
179			Py_FatalError("can't add __builtins__ to __main__");
180	}
181}
182
183/* Parse input from a file and execute it */
184
185int
186PyRun_AnyFile(fp, filename)
187	FILE *fp;
188	char *filename;
189{
190	if (filename == NULL)
191		filename = "???";
192	if (Py_FdIsInteractive(fp, filename))
193		return PyRun_InteractiveLoop(fp, filename);
194	else
195		return PyRun_SimpleFile(fp, filename);
196}
197
198int
199PyRun_InteractiveLoop(fp, filename)
200	FILE *fp;
201	char *filename;
202{
203	PyObject *v;
204	int ret;
205	v = PySys_GetObject("ps1");
206	if (v == NULL) {
207		PySys_SetObject("ps1", v = PyString_FromString(">>> "));
208		Py_XDECREF(v);
209	}
210	v = PySys_GetObject("ps2");
211	if (v == NULL) {
212		PySys_SetObject("ps2", v = PyString_FromString("... "));
213		Py_XDECREF(v);
214	}
215	for (;;) {
216		ret = PyRun_InteractiveOne(fp, filename);
217#ifdef Py_REF_DEBUG
218		fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
219#endif
220		if (ret == E_EOF)
221			return 0;
222		/*
223		if (ret == E_NOMEM)
224			return -1;
225		*/
226	}
227}
228
229int
230PyRun_InteractiveOne(fp, filename)
231	FILE *fp;
232	char *filename;
233{
234	PyObject *m, *d, *v, *w;
235	node *n;
236	perrdetail err;
237	char *ps1, *ps2;
238	v = PySys_GetObject("ps1");
239	w = PySys_GetObject("ps2");
240	if (v != NULL && PyString_Check(v)) {
241		Py_INCREF(v);
242		ps1 = PyString_AsString(v);
243	}
244	else {
245		v = NULL;
246		ps1 = "";
247	}
248	if (w != NULL && PyString_Check(w)) {
249		Py_INCREF(w);
250		ps2 = PyString_AsString(w);
251	}
252	else {
253		w = NULL;
254		ps2 = "";
255	}
256	Py_BEGIN_ALLOW_THREADS
257	n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar,
258			       Py_single_input, ps1, ps2, &err);
259	Py_END_ALLOW_THREADS
260	Py_XDECREF(v);
261	Py_XDECREF(w);
262	if (n == NULL) {
263		if (err.error == E_EOF) {
264			if (err.text)
265				free(err.text);
266			return E_EOF;
267		}
268		err_input(&err);
269		PyErr_Print();
270		return err.error;
271	}
272	m = PyImport_AddModule("__main__");
273	if (m == NULL)
274		return -1;
275	d = PyModule_GetDict(m);
276	v = run_node(n, filename, d, d);
277	if (v == NULL) {
278		PyErr_Print();
279		return -1;
280	}
281	Py_DECREF(v);
282	if (Py_FlushLine())
283		PyErr_Clear();
284	return 0;
285}
286
287int
288PyRun_SimpleFile(fp, filename)
289	FILE *fp;
290	char *filename;
291{
292	PyObject *m, *d, *v;
293	char *ext;
294
295	m = PyImport_AddModule("__main__");
296	if (m == NULL)
297		return -1;
298	d = PyModule_GetDict(m);
299	ext = filename + strlen(filename) - 4;
300	if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0
301#ifdef macintosh
302	/* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
303	    || getfiletype(filename) == 'PYC '
304	    || getfiletype(filename) == 'APPL'
305#endif /* macintosh */
306		) {
307		/* Try to run a pyc file. First, re-open in binary */
308		/* Don't close, done in main: fclose(fp); */
309		if( (fp = fopen(filename, "rb")) == NULL ) {
310			fprintf(stderr, "python: Can't reopen .pyc file\n");
311			return -1;
312		}
313		/* Turn on optimization if a .pyo file is given */
314		if (strcmp(ext, ".pyo") == 0)
315			Py_OptimizeFlag = 1;
316		v = run_pyc_file(fp, filename, d, d);
317	} else {
318		v = PyRun_File(fp, filename, Py_file_input, d, d);
319	}
320	if (v == NULL) {
321		PyErr_Print();
322		return -1;
323	}
324	Py_DECREF(v);
325	if (Py_FlushLine())
326		PyErr_Clear();
327	return 0;
328}
329
330int
331PyRun_SimpleString(command)
332	char *command;
333{
334	PyObject *m, *d, *v;
335	m = PyImport_AddModule("__main__");
336	if (m == NULL)
337		return -1;
338	d = PyModule_GetDict(m);
339	v = PyRun_String(command, Py_file_input, d, d);
340	if (v == NULL) {
341		PyErr_Print();
342		return -1;
343	}
344	Py_DECREF(v);
345	if (Py_FlushLine())
346		PyErr_Clear();
347	return 0;
348}
349
350void
351PyErr_Print()
352{
353	int err = 0;
354	PyObject *exception, *v, *tb, *f;
355	PyErr_Fetch(&exception, &v, &tb);
356	if (exception == NULL)
357		return;
358	if (exception == PyExc_SystemExit) {
359		err = Py_FlushLine();
360		fflush(stdout);
361		if (v == NULL || v == Py_None)
362			Py_Exit(0);
363		if (PyInt_Check(v))
364			Py_Exit((int)PyInt_AsLong(v));
365		else {
366			/* OK to use real stderr here */
367			PyObject_Print(v, stderr, Py_PRINT_RAW);
368			fprintf(stderr, "\n");
369			Py_Exit(1);
370		}
371	}
372	PySys_SetObject("last_type", exception);
373	PySys_SetObject("last_value", v);
374	PySys_SetObject("last_traceback", tb);
375	f = PySys_GetObject("stderr");
376	if (f == NULL)
377		fprintf(stderr, "lost sys.stderr\n");
378	else {
379		err = Py_FlushLine();
380		fflush(stdout);
381		if (err == 0)
382			err = PyTraceBack_Print(tb, f);
383		if (err == 0 && exception == PyExc_SyntaxError) {
384			PyObject *message;
385			char *filename, *text;
386			int lineno, offset;
387			if (!PyArg_Parse(v, "(O(ziiz))", &message,
388				     &filename, &lineno, &offset, &text))
389				PyErr_Clear();
390			else {
391				char buf[10];
392				PyFile_WriteString("  File \"", f);
393				if (filename == NULL)
394					PyFile_WriteString("<string>", f);
395				else
396					PyFile_WriteString(filename, f);
397				PyFile_WriteString("\", line ", f);
398				sprintf(buf, "%d", lineno);
399				PyFile_WriteString(buf, f);
400				PyFile_WriteString("\n", f);
401				if (text != NULL) {
402					char *nl;
403					if (offset > 0 &&
404					    offset == (int)strlen(text))
405						offset--;
406					for (;;) {
407						nl = strchr(text, '\n');
408						if (nl == NULL ||
409						    nl-text >= offset)
410							break;
411						offset -= (nl+1-text);
412						text = nl+1;
413					}
414					while (*text == ' ' || *text == '\t') {
415						text++;
416						offset--;
417					}
418					PyFile_WriteString("    ", f);
419					PyFile_WriteString(text, f);
420					if (*text == '\0' ||
421					    text[strlen(text)-1] != '\n')
422						PyFile_WriteString("\n", f);
423					PyFile_WriteString("    ", f);
424					offset--;
425					while (offset > 0) {
426						PyFile_WriteString(" ", f);
427						offset--;
428					}
429					PyFile_WriteString("^\n", f);
430				}
431				Py_INCREF(message);
432				Py_DECREF(v);
433				v = message;
434				/* Can't be bothered to check all those
435				   PyFile_WriteString() calls */
436				if (PyErr_Occurred())
437					err = -1;
438			}
439		}
440		if (err) {
441			/* Don't do anything else */
442		}
443		else if (PyClass_Check(exception)) {
444			PyObject* className =
445				((PyClassObject*)exception)->cl_name;
446			if (className == NULL)
447				err = PyFile_WriteString("<unknown>", f);
448			else
449				err = PyFile_WriteObject(className, f,
450							 Py_PRINT_RAW);
451		}
452		else
453			err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
454		if (err == 0) {
455			if (v != NULL && v != Py_None) {
456				err = PyFile_WriteString(": ", f);
457				if (err == 0)
458				  err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
459			}
460		}
461		if (err == 0)
462			err = PyFile_WriteString("\n", f);
463	}
464	Py_XDECREF(exception);
465	Py_XDECREF(v);
466	Py_XDECREF(tb);
467	/* If an error happened here, don't show it.
468	   XXX This is wrong, but too many callers rely on this behavior. */
469	if (err != 0)
470		PyErr_Clear();
471}
472
473PyObject *
474PyRun_String(str, start, globals, locals)
475	char *str;
476	int start;
477	PyObject *globals, *locals;
478{
479	return run_err_node(PyParser_SimpleParseString(str, start),
480			    "<string>", globals, locals);
481}
482
483PyObject *
484PyRun_File(fp, filename, start, globals, locals)
485	FILE *fp;
486	char *filename;
487	int start;
488	PyObject *globals, *locals;
489{
490	return run_err_node(PyParser_SimpleParseFile(fp, filename, start),
491			    filename, globals, locals);
492}
493
494static PyObject *
495run_err_node(n, filename, globals, locals)
496	node *n;
497	char *filename;
498	PyObject *globals, *locals;
499{
500	if (n == NULL)
501		return  NULL;
502	return run_node(n, filename, globals, locals);
503}
504
505static PyObject *
506run_node(n, filename, globals, locals)
507	node *n;
508	char *filename;
509	PyObject *globals, *locals;
510{
511	PyCodeObject *co;
512	PyObject *v;
513	co = PyNode_Compile(n, filename);
514	PyNode_Free(n);
515	if (co == NULL)
516		return NULL;
517	v = PyEval_EvalCode(co, globals, locals);
518	Py_DECREF(co);
519	return v;
520}
521
522static PyObject *
523run_pyc_file(fp, filename, globals, locals)
524	FILE *fp;
525	char *filename;
526	PyObject *globals, *locals;
527{
528	PyCodeObject *co;
529	PyObject *v;
530	long magic;
531	long PyImport_GetMagicNumber();
532
533	magic = PyMarshal_ReadLongFromFile(fp);
534	if (magic != PyImport_GetMagicNumber()) {
535		PyErr_SetString(PyExc_RuntimeError,
536			   "Bad magic number in .pyc file");
537		return NULL;
538	}
539	(void) PyMarshal_ReadLongFromFile(fp);
540	v = PyMarshal_ReadObjectFromFile(fp);
541	fclose(fp);
542	if (v == NULL || !PyCode_Check(v)) {
543		Py_XDECREF(v);
544		PyErr_SetString(PyExc_RuntimeError,
545			   "Bad code object in .pyc file");
546		return NULL;
547	}
548	co = (PyCodeObject *)v;
549	v = PyEval_EvalCode(co, globals, locals);
550	Py_DECREF(co);
551	return v;
552}
553
554PyObject *
555Py_CompileString(str, filename, start)
556	char *str;
557	char *filename;
558	int start;
559{
560	node *n;
561	PyCodeObject *co;
562	n = PyParser_SimpleParseString(str, start);
563	if (n == NULL)
564		return NULL;
565	co = PyNode_Compile(n, filename);
566	PyNode_Free(n);
567	return (PyObject *)co;
568}
569
570/* Simplified interface to parsefile -- return node or set exception */
571
572node *
573PyParser_SimpleParseFile(fp, filename, start)
574	FILE *fp;
575	char *filename;
576	int start;
577{
578	node *n;
579	perrdetail err;
580	Py_BEGIN_ALLOW_THREADS
581	n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar, start,
582				(char *)0, (char *)0, &err);
583	Py_END_ALLOW_THREADS
584	if (n == NULL)
585		err_input(&err);
586	return n;
587}
588
589/* Simplified interface to parsestring -- return node or set exception */
590
591node *
592PyParser_SimpleParseString(str, start)
593	char *str;
594	int start;
595{
596	node *n;
597	perrdetail err;
598	n = PyParser_ParseString(str, &_PyParser_Grammar, start, &err);
599	if (n == NULL)
600		err_input(&err);
601	return n;
602}
603
604/* Set the error appropriate to the given input error code (see errcode.h) */
605
606static void
607err_input(err)
608	perrdetail *err;
609{
610	PyObject *v, *w;
611	char *msg = NULL;
612	v = Py_BuildValue("(ziiz)", err->filename,
613			    err->lineno, err->offset, err->text);
614	if (err->text != NULL) {
615		free(err->text);
616		err->text = NULL;
617	}
618	switch (err->error) {
619	case E_SYNTAX:
620		msg = "invalid syntax";
621		break;
622	case E_TOKEN:
623		msg = "invalid token";
624
625		break;
626	case E_INTR:
627		PyErr_SetNone(PyExc_KeyboardInterrupt);
628		return;
629	case E_NOMEM:
630		PyErr_NoMemory();
631		return;
632	case E_EOF:
633		msg = "unexpected EOF while parsing";
634		break;
635	default:
636		fprintf(stderr, "error=%d\n", err->error);
637		msg = "unknown parsing error";
638		break;
639	}
640	w = Py_BuildValue("(sO)", msg, v);
641	Py_XDECREF(v);
642	PyErr_SetObject(PyExc_SyntaxError, w);
643	Py_XDECREF(w);
644}
645
646/* Print fatal error message and abort */
647
648void
649Py_FatalError(msg)
650	char *msg;
651{
652	fprintf(stderr, "Fatal Python error: %s\n", msg);
653#ifdef macintosh
654	for (;;);
655#endif
656#ifdef MS_WIN32
657	OutputDebugString("Fatal Python error: ");
658	OutputDebugString(msg);
659	OutputDebugString("\n");
660#endif
661	abort();
662}
663
664/* Clean up and exit */
665
666#ifdef WITH_THREAD
667#include "thread.h"
668int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
669#endif
670
671#define NEXITFUNCS 32
672static void (*exitfuncs[NEXITFUNCS])();
673static int nexitfuncs = 0;
674
675int Py_AtExit(func)
676	void (*func) Py_PROTO((void));
677{
678	if (nexitfuncs >= NEXITFUNCS)
679		return -1;
680	exitfuncs[nexitfuncs++] = func;
681	return 0;
682}
683
684void
685Py_Cleanup()
686{
687	PyObject *exitfunc = PySys_GetObject("exitfunc");
688
689	if (exitfunc) {
690		PyObject *res;
691		Py_INCREF(exitfunc);
692		PySys_SetObject("exitfunc", (PyObject *)NULL);
693		res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
694		if (res == NULL) {
695			fprintf(stderr, "Error in sys.exitfunc:\n");
696			PyErr_Print();
697		}
698		Py_DECREF(exitfunc);
699	}
700
701	Py_FlushLine();
702
703	while (nexitfuncs > 0)
704		(*exitfuncs[--nexitfuncs])();
705}
706
707#ifdef COUNT_ALLOCS
708extern void dump_counts Py_PROTO((void));
709#endif
710
711void
712Py_Exit(sts)
713	int sts;
714{
715	Py_Cleanup();
716
717#ifdef COUNT_ALLOCS
718	dump_counts();
719#endif
720
721#ifdef WITH_THREAD
722
723	/* Other threads may still be active, so skip most of the
724	   cleanup actions usually done (these are mostly for
725	   debugging anyway). */
726
727	(void) PyEval_SaveThread();
728#ifndef NO_EXIT_PROG
729	if (_PyThread_Started)
730		_exit_prog(sts);
731	else
732		exit_prog(sts);
733#else /* !NO_EXIT_PROG */
734	if (_PyThread_Started)
735		_exit(sts);
736	else
737		exit(sts);
738#endif /* !NO_EXIT_PROG */
739
740#else /* WITH_THREAD */
741
742	PyImport_Cleanup();
743
744	PyErr_Clear();
745
746#ifdef Py_REF_DEBUG
747	fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
748#endif
749
750#ifdef Py_TRACE_REFS
751	if (_Py_AskYesNo("Print left references?")) {
752		_Py_PrintReferences(stderr);
753	}
754#endif /* Py_TRACE_REFS */
755
756#ifdef macintosh
757	PyMac_Exit(sts);
758#else
759	exit(sts);
760#endif
761#endif /* WITH_THREAD */
762	/*NOTREACHED*/
763}
764
765#ifdef HAVE_SIGNAL_H
766static RETSIGTYPE
767sighandler(sig)
768	int sig;
769{
770	signal(sig, SIG_DFL); /* Don't catch recursive signals */
771	Py_Cleanup(); /* Do essential clean-up */
772#ifdef HAVE_KILL
773	kill(getpid(), sig); /* Pretend the signal killed us */
774#else
775	exit(1);
776#endif
777	/*NOTREACHED*/
778}
779#endif
780
781static void
782initsigs()
783{
784	RETSIGTYPE (*t)();
785#ifdef HAVE_SIGNAL_H
786#ifdef SIGPIPE
787	signal(SIGPIPE, SIG_IGN);
788#endif
789#ifdef SIGHUP
790	t = signal(SIGHUP, SIG_IGN);
791	if (t == SIG_DFL)
792		signal(SIGHUP, sighandler);
793	else
794		signal(SIGHUP, t);
795#endif
796#ifdef SIGTERM
797	t = signal(SIGTERM, SIG_IGN);
798	if (t == SIG_DFL)
799		signal(SIGTERM, sighandler);
800	else
801		signal(SIGTERM, t);
802#endif
803#endif /* HAVE_SIGNAL_H */
804	PyOS_InitInterrupts(); /* May imply initsignal() */
805}
806
807#ifdef Py_TRACE_REFS
808/* Ask a yes/no question */
809
810int
811_Py_AskYesNo(prompt)
812	char *prompt;
813{
814	char buf[256];
815
816	printf("%s [ny] ", prompt);
817	if (fgets(buf, sizeof buf, stdin) == NULL)
818		return 0;
819	return buf[0] == 'y' || buf[0] == 'Y';
820}
821#endif
822
823#ifdef MPW
824
825/* Check for file descriptor connected to interactive device.
826   Pretend that stdin is always interactive, other files never. */
827
828int
829isatty(fd)
830	int fd;
831{
832	return fd == fileno(stdin);
833}
834
835#endif
836
837/*
838 * The file descriptor fd is considered ``interactive'' if either
839 *   a) isatty(fd) is TRUE, or
840 *   b) the -i flag was given, and the filename associated with
841 *      the descriptor is NULL or "<stdin>" or "???".
842 */
843int
844Py_FdIsInteractive(fp, filename)
845	FILE *fp;
846	char *filename;
847{
848	if (isatty((int)fileno(fp)))
849		return 1;
850	if (!Py_InteractiveFlag)
851		return 0;
852	return (filename == NULL) ||
853	       (strcmp(filename, "<stdin>") == 0) ||
854	       (strcmp(filename, "???") == 0);
855}
856