Skip to content

Commit 8d57866

Browse files
author
georg.brandl
committed
Patch #703779: unset __file__ in __main__ after running a file. This
makes the filenames the warning module prints much more sensible when a PYTHONSTARTUP file is used. git-svn-id: http://svn.python.org/projects/python/trunk@54189 6015fed2-1504-0410-9fe1-9d1591cc4771
1 parent f0a15ac commit 8d57866

2 files changed

Lines changed: 15 additions & 3 deletions

File tree

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ What's New in Python 2.6 alpha 1?
1212
Core and builtins
1313
-----------------
1414

15+
- Patch #703779: unset __file__ in __main__ after running a file. This
16+
makes the filenames the warning module prints much more sensible when
17+
a PYTHONSTARTUP file is used.
18+
1519
- Variant of patch #697613: don't exit the interpreter on a SystemExit
1620
exception if the -i command line option or PYTHONINSPECT environment
1721
variable is given, but break into the interactive interpreter just like

Python/pythonrun.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -849,6 +849,7 @@ PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
849849
{
850850
PyObject *m, *d, *v;
851851
const char *ext;
852+
int set_file_name = 0, ret;
852853

853854
m = PyImport_AddModule("__main__");
854855
if (m == NULL)
@@ -862,6 +863,7 @@ PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
862863
Py_DECREF(f);
863864
return -1;
864865
}
866+
set_file_name = 1;
865867
Py_DECREF(f);
866868
}
867869
ext = filename + strlen(filename) - 4;
@@ -871,7 +873,8 @@ PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
871873
fclose(fp);
872874
if ((fp = fopen(filename, "rb")) == NULL) {
873875
fprintf(stderr, "python: Can't reopen .pyc file\n");
874-
return -1;
876+
ret = -1;
877+
goto done;
875878
}
876879
/* Turn on optimization if a .pyo file is given */
877880
if (strcmp(ext, ".pyo") == 0)
@@ -883,12 +886,17 @@ PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
883886
}
884887
if (v == NULL) {
885888
PyErr_Print();
886-
return -1;
889+
ret = -1;
890+
goto done;
887891
}
888892
Py_DECREF(v);
889893
if (Py_FlushLine())
890894
PyErr_Clear();
891-
return 0;
895+
ret = 0;
896+
done:
897+
if (set_file_name && PyDict_DelItemString(d, "__file__"))
898+
PyErr_Clear();
899+
return ret;
892900
}
893901

894902
int

0 commit comments

Comments
 (0)