我试图从解释器内使用Python命令执行一个文件。

编辑:我试图使用变量和设置从该文件,而不是调用一个单独的进程。


当前回答

假设你想要以下特性:

源文件在调试器中正常运行(文件名显示在堆栈中,等等) __name__ == '__main__'为True,因此脚本的行为与脚本相同。

exec(open('foo.py').read())特性1失败 导入foo策略失败特性2

要做到这两点,你需要:

    source = open(filename).read()
    code = compile(source, filename, 'exec')
    exec(code)

其他回答

对于python3,可以使用任意一种,同时加上xxxx =你的文件名。

exec(open('./xxxx.py').read())

假设你想要以下特性:

源文件在调试器中正常运行(文件名显示在堆栈中,等等) __name__ == '__main__'为True,因此脚本的行为与脚本相同。

exec(open('foo.py').read())特性1失败 导入foo策略失败特性2

要做到这两点,你需要:

    source = open(filename).read()
    code = compile(source, filename, 'exec')
    exec(code)

对于Python 2:

>>> execfile('filename.py')

对于Python 3:

>>> exec(open("filename.py").read())
# or
>>> from pathlib import Path
>>> exec(Path("filename.py").read_text())

请参见文档。如果您使用的是Python 3.0,请参阅此问题。

参见@S的回答。Lott提供了一个示例,说明如何在执行完filename.py后访问全局变量。

对于Python 3:

>>> exec(open("helloworld.py").read())

在运行该命令之前,请确保您在正确的目录中。

要从不同的目录运行一个文件,你可以使用下面的命令:

with open ("C:\\Users\\UserName\\SomeFolder\\helloworld.py", "r") as file:
    exec(file.read())

几种方式。

从外壳开始 python someFile.py 在IDLE中,按F5。 如果你是交互式输入,试试这个(Python3): > > > exec (open (filename.py) .read ()) 对于Python 2: >>>变量= {} execfile("someFile.py",变量) >>>打印someFile模块中的变量# globals