简体   繁体   中英

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 (ie, '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.

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

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