当我运行终端然后访问 python3 shell 时,我可以使用导入运行文件或模块,但如果我再次尝试运行它,则没有任何反应。
我之前看到这个问题:[ Need to restart python in Terminal every time a change is made to script
然后我阅读了文档:[ https://docs.python.org/3/tutorial/modules.html#executing-modules-as-scripts][1]
但两者都在谈论重新启动模块中的单个功能。我说的是重新运行整个文件。 我在文件末尾包含了这段代码,但仍然没有任何反应
if __name__ == "__main__":
pass
更新: 在我按照评论运行文件后,这就是我得到的:
Ms-MBP:mine M$ python3
Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> python python_file.py
File "<stdin>", line 1
python python_file.py
^
SyntaxError: invalid syntax
>>>
最佳答案
如评论中所述,如果您在终端中工作,您应该使用命令(记住从主 shell 执行此操作,即可能是 bash,而不是从 Python shell)
$ python script.py
这是执行 python 文件的预期方式。您通常可以使用键盘上的向上箭头快速循环回到上一个命令。
但是,如果您出于某种原因确实需要从交互式解释器运行您的脚本,则有一些选项,但请注意它们有点老套,可能不是运行代码的最佳方式,尽管这可能因您的具体用例而异。
如果您的脚本 hello.py
具有以下来源:
print("hello world")
在 python3 中,您可以从 shell 执行以下操作:
>>> from importlib import reload
>>> import hello
hello world
>>> reload(hello)
hello world
<module 'hello' from '/home/izaak/programmeren/stackoverflow/replrun/hello.py'>
Here是importlib.reload
的文档。如您所见,这复制了脚本的副作用。第二部分是模块的 repr()
,因为 reload()
函数返回模块 - 这没什么好担心的,它是方法的一部分口译员工作,因为它打印你输入的任何东西的值(value) - 例如你可以做
>>> 2 + 3
5
而不是必须明确地 print(2 + 3)
。如果这真的困扰你,你可以做
>>> from importlib import reload as _reload
>>> def reload(mod):
... _reload(mod)
...
>>> import hello
hello world
>>> reload(hello)
hello world
但是,使用您找到的 if
语句(这也是评论中的建议),您的脚本看起来像这样更符合习惯:
def main():
print("hello world")
if __name__ == "__main__":
main()
这样,您可以从 Python shell 执行以下操作:
>>> import hello
>>> hello.main()
hello world
>>> hello.main()
hello world
这是非常好的做法。此处的 if
语句检查脚本是否作为“主”脚本执行(就像直接从命令行运行它,如我的第一个建议),如果是,则执行主函数。这意味着如果另一个脚本想要导入
它,该脚本将不会执行任何操作,从而使其更像一个模块。
如果您使用的是 IPython,您可能会知道这一点,但这会变得容易得多,您可以做到
In [1]: %run hello.py
hello world
关于python - 如何避免在每次导入后重新启动 python shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45776493/