简体   繁体   中英

In Python, how can I run another Python script from the main script at the same time and close it when I stop the main script?

import subprocess 

subprocess.Popen('python', 'second_script.py')

Does this open the second script and makes them run concurrently? Also will it close the second script if I stop the main one? If not, how can I do that?

I don't clearly understand what you need.

If you want to use some functions that are coded in 'pythonScriptA.py' in another script 'pythonScriptB.py', you can import the first script:

from pythonScriptA import *

# Use the functions in the ScriptB

If you want two script to run concurrently/in parallel, you should look into the multiprocessing library, or in any other library that allow python code to be run on multiple threads.

-- Edit: correction of the script

You should do something like this

#! /usr/bin/env python3

import subprocess

pid = subprocess.Popen(['second-script']).pid
print(f'pid={pid}')
...
# do whatever you have to do here

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