Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 905
masterial Avatar asked Jul 30 '10 18:07

masterial


People also ask

How do you automatically restart Python code?

Now, in a Python Shell, you would have to press either the Run button and then 'Run Module (F5)' or just the F5 key on your keyboard. That is the first time you run it. When the program ended, you would go back to your Cheese.py file and then press F5 to run the program again.

How do I keep a Python script open after command?

cmd /k is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type cmd /k and then drag&drop the script you want to the Run dialog. Fantastic answer. You should have got this.

Why does Python shell restart?

When the IDLE process loses communication with the user process, it restarts the interactive Shell. This is intentional. If IDLE is installed and functioning correctly, the only other way to see the RESTART: Shell line is to explicitly select Restart Shell from the menu.

How do you rerun a program in Python?

Restart the Program Script in Python Using the os. execv() Function. The os. execv(path, args) function executes the new program by replacing the process.


1 Answers

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.

like image 104
Will McCutchen Avatar answered Oct 12 '22 23:10

Will McCutchen