我编写了一个脚本并将其保存为 test.py(代码如下所示)。当我从脚本(运行模块 5)运行它时,我在 Python Shell 中得到了结果。
但我已经尝试了多种在线建议,让它从 Python Shell 运行,但我失败了(下面粘贴了一个错误)。
如何从 python shell 运行 python 脚本? 我运行的 Python 版本是 3.7.3,在 Windows 中。
#!/usr/bin/python3
print(" Hello, world!")
exec(open(test.py).read())
输出:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
exec(open(test.py).read())
NameError: name 'test' is not defined
最佳答案
你不需要最后一行来运行它。您只需要:
!/usr/bin/python3
print(" Hello, world!")
如果你想从另一个文件运行它,不要使用 exec。相反,导入它。
import test
关于python - 从 Python Shell 运行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56498247/