Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a python script and changing git branch

I am trying to find ways to make better use of my time while programming.

I have a python script that does some heavy work (it can take hours) to finish. Now, most of the work it does is network related, so i have plenty of cpu resources to spare.

If the script was a C binary executable, it would be fine to git checkout onto a different branch and do extra work, I could even modify the binary in disk as it has been copied to ram, so until it finishes running I won't affect program output.

But python scripts are translated, not compiled. What happens if I start tampering with the source file, can i corrupt the programs output, or is the text file and associated imports copied to RAM, allowing me to tamper with the source with no risk of changing the behaviour of the running program?

like image 261
Makogan Avatar asked Dec 05 '18 17:12

Makogan


People also ask

Can I modify Python script while running?

If you modify a script and save while it's running, and the previous version errors, in the traceback readout, it opens the current version of the file and makes the traceback look different than when you started.

How do I switch to a different branch in Git?

Git checkout works hand-in-hand with git branch . The git branch command can be used to create a new branch. When you want to start a new feature, you create a new branch off main using git branch new_branch . Once created you can then use git checkout new_branch to switch to that branch.


2 Answers

In general, if you have a single Python file which you run as a script, you're fine. When you run the file, it is compiled into bytecode which is then executed. You can change the original script at this point and nothing breaks.

However, we can deliberately break it by writing some horrible but legal code like this:

horrible.py:

from time import sleep


sleep(10)
import silly
silly.thing()

silly.py:

def thing():
    print("Wow!")

You can run horrible.py and while it is running you can edit silly.py on disk to make it do something else. When silly.py is finally imported, the updated version will be loaded.

A workaround is to put all your imports at the top of the file, which you probably do anyway.

like image 55
Rob Bricheno Avatar answered Sep 22 '22 14:09

Rob Bricheno


When a python program is run it is compiled (kinda, more like translated) into a .pyc file that is then run by the python interpreter. When you change a file it should NOT affect the code if it is already running.

Here is a related stackoverflow answer. What will happen if I modify a Python script while it's running?

like image 29
PeterH Avatar answered Sep 20 '22 14:09

PeterH