Skip to main content
 首页 » 编程设计

python之在线程中调用 bash

2025年05月04日20sxdcgaq8080

我需要从我的 Python 脚本中调用 bash 脚本。

import subprocess  
subprocess.call("path/to/script.sh") 

这是有效的,但脚本正在启动另一个程序,因此不会退出。所以我的主循环被子进程阻塞了。

有没有办法将脚本调用为线程,而不是 Python 中的子进程?

请您参考如下方法:

你最好使用 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

但如果你坚持使用threads,这也可能有效:

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')