加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何避免每次导入后重新启动python shell

发布时间:2020-12-20 12:02:41 所属栏目:Python 来源:网络整理
导读:当我运行终端然后访问 python3 shell时,我可以使用import运行文件或模块,但是如果我尝试再次运行它,则没有任何反应. 我之前看过这个问题:[Need to restart python in Terminal every time a change is made to script 我读了文档:[https://docs.python.org
当我运行终端然后访问 python3 shell时,我可以使用import运行文件或模块,但是如果我尝试再次运行它,则没有任何反应.

我之前看过这个问题:[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文件的预期方法.您通常可以使用键盘上的向上箭头快速循环回到上一个命令.

但是,如果由于某些原因确实需要从交互式解释器运行脚本,那么有一些选项,虽然要注意它们有点hacky并且可能不是运行代码的最佳方式,尽管这可能因你的具体用例是.

如果您的脚本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()函数返回模块 – 这没什么好担心的,它是解释器工作方式的一部分,因为它打印你输入的任何内容的值它 – 例如你可以做到

>>> 2 + 3
5

而不是必须明确打印(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语句检查脚本是否作为“主”脚本执行(如直接从命令行运行,如我的第一个建议),如果是,则执行main函数.这意味着如果另一个脚本想要导入它,脚本将不会执行任何操作,从而使其更像一个模块.

如果您正在使用IPython,您可能会知道这一点,但这会变得更容易,您可以做到

In [1]: %run hello.py
hello world

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读