在 IDLE 的正常模式下 运行 启动文件时无法使用 __file__

Cannot use __file__ when running startup file in IDLE's normal mode

我写了一个小批处理文件 (Windows 8.1) 来直接在 IDLE 中启动我的脚本:

START "" pythonw.exe "C:\Program Files (x86)\Python36-32\Lib\idlelib\idle.py" -r my_script.py

脚本包含

my_dir = os.path.split(__file__)[0]

这会产生名称错误

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "my_script.py", line 245, in out_file_dia
    my_dir = os.path.split(__file__)[0]
NameError: name '__file__' is not defined

如果我先打开 IDLE 然后再启动脚本,它就可以正常工作。为什么是

__file__

在这种情况下没有定义?

在交互模式下,输入'file'是用户输入的语句流,所以__file__没有设置。如果有 PYTHONSTARTUP 文件,当文件为 运行 时 __file__ 设置为该文件名,然后在第一个 >>> 提示符之前取消设置。当前,当 运行在单独的进程中运行用户代码时,IDLE 不会执行此操作,这是现在的正常模式。

我打开 https://bugs.python.org/issue32984 来解决这个问题。到时候我会尽量记得在这里报告。

当 IDLE 以 -n 启动时,要使用旧的已弃用模式,在 IDLE GUI 进程中执行用户代码,启动文件和交互式输入请参阅 __file__ 设置为 idlelib 文件。两者都错了,但不会被修复。

编辑:PR-5981,在 Windows 上对我有用,修改 pyshell.execfile 开始如下:

def execfile(self, filename, source=None):  # currently line 633
    "Execute an existing file"
    if source is None:
        with tokenize.open(filename) as fp:
            source = fp.read()
            if use_subprocess:
                source = (f"__file__ = r'''{os.path.abspath(filename)}'''\n"
                          + source + "\ndel __file__")

最后 3 行是新的。 uwain12345,添加它们应该可以解决您的问题。如果没有,我想知道。

编辑 2:tweek 替换代码以允许在启动文件名中包含 '。

注意:f 字符串是 3.6 中新增的。对于较旧的 Python,将 source 行替换为

                filename = os.path.abspath(filename)
                source = ("__file__ = r'''{}'''\n".format(filename)