我之前看过这个问题:[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$python3Python 3.6.2 (v3.6.2:5fd33b5926,Jul 16 2017,20:11:06) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType "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文件的预期方法.您通常可以使用键盘上的向上箭头快速循环回到上一个命令.
但是,如果由于某些原因确实需要从交互式解释器运行脚本,那么有一些选项,虽然要注意它们有点Hacky并且可能不是运行代码的最佳方式,尽管这可能因你的具体用例是.
如果您的脚本hello.py具有以下源:
print("hello world")
在python3中,您可以从shell执行以下 *** 作:
>>> from importlib import reload>>> import hellohello world>>> reload(hello)hello world<module 'hello' from '/home/izaak/programmeren/stackoverflow/replrun/hello.py'>
Here是importlib.reload的文档.如您所见,这复制了脚本的副作用.第二部分是模块的repr(),因为reload()函数返回模块 – 这没什么好担心的,它是解释器工作方式的一部分,因为它打印你输入的任何内容的值它 – 例如你可以做到
>>> 2 + 35
而不是必须明确打印(2 3).如果这真的打扰你,你可以做到
>>> from importlib import reload as _reload>>> def reload(mod):... _reload(mod)... >>> import hellohello 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语句检查脚本是否作为“主”脚本执行(如直接从命令行运行,如我的第一个建议),如果是,则执行main函数.这意味着如果另一个脚本想要导入它,脚本将不会执行任何 *** 作,从而使其更像一个模块.
如果您正在使用IPython,您可能会知道这一点,但这会变得更容易,您可以做到
In [1]: %run hello.pyhello world总结
以上是内存溢出为你收集整理的如何避免每次导入后重新启动python shell全部内容,希望文章能够帮你解决如何避免每次导入后重新启动python shell所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)