0

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.

Xander
  • 593
  • 1
  • 5
  • 19

1 Answers1

1

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
Community
  • 1
  • 1
Eugene K
  • 3,381
  • 2
  • 23
  • 36
  • Hi Eugene, Thanks for your answer. I have tried to avoid subprocess.Popen because I never was able to figure out how to solve the permission error [errno 13: Permission Denied], when attempting to execute another .py file. Is there another way to go about doing this? – Xander Oct 10 '15 at 09:01
  • 1
    @Xander: executing files may be different depending on architecture. Are you using Windows or a Unix-like system? – Serge Ballesta Oct 10 '15 at 09:14
  • My apologies, I should have specified. I am using OSX 10.9 and 'old.py' and 'new.py' are in the same directory in the user's home folder. – Xander Oct 10 '15 at 11:22
  • 1
    @Xander Run `chmod +x old.py` from the terminal to set the executable bit. – Eugene K Oct 10 '15 at 16:39
  • @Eugene K: I had to do a little bit more finagling to get the code to work, but it turns out that Popen was a good solution for this dilemma. `from sys import executable from subprocess import Popen Popen([executable, 'old.py'])` Thank you for your help! – Xander Oct 10 '15 at 23:52
  • 1
    @Xander I see, I think the issue then was that your hashbang was not correct. I used `#!/usr/bin/python`, but where your `python` binary is located is probably different. Or you may not have put that in? – Eugene K Oct 11 '15 at 01:13