Reputation: 25
I need to call a bash Script Out of my Python Script.
import subprocess
subprocess.call("path/to/script.sh")
This is working, but the Script is starting another programm and therefore wont Exit. So my main Loop is blocked by the subprocess.
Is there a way to call the Script as Thread, not subprocess in Python?
Upvotes: 2
Views: 3421
Reputation: 531055
Don't use call
; its only purpose is to block until the command exits. Use Popen
directly:
import subprocess
p = subprocess.Popen("path/to/script.sh")
Now script.sh
runs in the forked process while your Python script continues. Use p.wait()
when you are ready to check if the script has completed.
Upvotes: 0
Reputation: 11553
You're better off using Popen
Execute a child program in a new process. On Unix, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows
But if you insist on using threads
this might also work:
import subprocess
import threading
def basher():
subprocess.call("echo hello > /tmp/test.txt", shell=True)
t = threading.Thread(target=basher)
t.start()
print('started')
# doing something else
t.join()
print('finished')
Upvotes: 7
Reputation: 119
Since you specifically asked for a separate thread, I recommend using the multiprocessing
module (documentation):
from multiprocessing import Process
import subprocess
def myTask():
subprocess.call("path/to/script.sh")
p = Process(target=myTask) # creates a new thread which will run the function myTask
p.start() # starts the thread
# the script is now running in a separate thread
# you can now continue doing what you want
If at some point in your python script (e.g. before exiting) you want to make sure that the bash script has finished running you can call p.join()
which blocks the python script until the bash script has terminated.
Upvotes: -1