pythonpython-2.7execfile

How to execfile an independent .py and continue on to next line of code in the original .py?


I have two python files: 'old.py' and 'new.py'. I would like to execute 'new.py' from 'old.py' using execfile("new.py"). However, rather than waiting for 'new.py' to completely finish its program before moving to the next line in 'old.py', I would like both scripts to continue independently (i.e., 'old.py' moves to the line after the execfile('new.py') command immediately.

For instance, if 'new.py' takes 48 seconds to complete its program in entirety, and 'old.py' reads:

execfile("new.py")
print 2+2

I would like "4" to be printed immediately, rather than 48 seconds later.

How would you recommend doing this?

Thank you for sharing your knowledge and expertise.


Solution

  • You want to utilize subprocess.Popen. It will open a process in a separate process.

    # old.py - Make sure it's chmod +x
    #!/usr/bin/python
    import time
    
    time.sleep(48)
    

    # new.py 
    #!/usr/bin/python
    import subprocess
    
    subprocess.Popen(["./old.py"])
    print(2+2)
    

    >>> python new.py 
    4
    >>> ps
      PID TTY          TIME CMD
     2495 pts/17   00:00:00 bash
     2696 pts/17   00:00:00 old.py
     2697 pts/17   00:00:00 ps