'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?
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Diego Torres Milano |
| Solution 2 |
