简体   繁体   中英

Need to restart python in Terminal every time a change is made to script

Every time I make a change to a python script I have to reload python and re-import the module. Please advise how I can modify my scripts and run then without having to relaunch python in the terminal.

Thanks.

I've got a suggestion, based on your comment describing your work flow:

first, i run python3.1 in terminal second, i do "import module" then, i run a method from the module lets say "module.method(arg)" every time, i try to debug the code, i have to do this entire sequence, even though the change is minor. it is highly inefficient

Instead of firing up the interactive Python shell, make the module itself executable. The easiest way to do this is to add a block to the bottom of the module like so:

if __name__ == '__main__':
    method(arg) # matches what you run manually in the Python shell

Then, instead of running python3.1, then importing the module, then calling the method, you can do something like this:

python3.1 modulename.py

and Python will run whatever code is in the if __name__ == '__main__' block. But that code will not be run if the module is imported by another Python module. More information on this common Python idiom can be found in the Python tutorial .

The advantage of this is that when you make a change to your code, you can usually just re-run the module by pressing the up arrow and hitting enter. No messy reloading necessary.

如果它只是一些正在改变的模块,你可以在脚本中调用reload(module)

你的意思是你直接在交互式python中输入脚本,或者你是通过运行python myscript.py类的东西从终端执行.py文件的?

You can use reload to re-import a module. I use it frequently when using the interactive mode to debug code.

However, from a higher level, I would be hesitant to use that in a production version of a program. Unless you will have very strict control over how sub-modules are changing, it would not be hard to have the reloaded module change in some way that breaks your program. Unless your program really needs 100% up-time, it would make sense to stop it and start it again when there is some kind of version change.

I found a bypass online. Magic commands exist. It works like a charm for me. The Reload option didn't work for me. Got it from here and point 3 of this link.

Basically all you have to do is the following: and changes you make are reflected automatically after you save.

In [1]: %load_ext autoreload

In [2]: %autoreload 2

In [3]: Import MODULE

In [4]: my_class = Module.class()
        my_class.printham()
Out[4]: ham

In [5]: #make changes to printham and save
In [6]: my_class.printham() 
Out[6]: hamlet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM