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

问题描述 投票:0回答:1

我写了一个小批处理文件(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__

在这种情况下没有定义?

python python-idle
1个回答
2
投票

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

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

当使用-n启动IDLE时,要使用在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中的新字符串。对于较老的蟒蛇,用source替换

                filename = os.path.abspath(filename)
                source = ("__file__ = r'''{}'''\n".format(filename)
© www.soinside.com 2019 - 2024. All rights reserved.