简体   繁体   中英

How to run a Python script from inside of another Python Script?

I am currently using subprocess to run a Python script inside of my current Python but it is keep giving me an error:

for dir in os.listdir(os.path.join(DIR2,dirname)):
    temp = os.path.join(os.path.join(DIR2,dirname),dir)
    files = [os.path.join(temp, f) for f in os.listdir(temp) if f.endswith("json")]
    for lists in files:
        subprocess.Popen(["python", DIR4, os.path.join(temp,lists)])

Above is what I am currently using. DIR4 is the path of the python that I want to run.

Problem is, the python that I want to run can only take one file at a time. However this subprocess looks like it tries to execute ALL at ONCE.

I want to run ONE at a time, instead of ALL at ONCE. Because it is running ALL at ONCE, my python that I want to run does not work the way it is..

What do I need to do to change this?

If you want to wait first for the subprocess to terminate, before going ahead, I think you could use Popen.wait():

...
p = subprocess.Popen(["python", DIR4, os.path.join(temp,lists)])
p.wait()
...

To actually do what you're asking, and not hack it together through subprocess, you can use exec which allows you to run python code with your own provided globals and locals.

In older versions of Python (meaning pre-3), you can use execfile to achieve the same thing .

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