python - 在线程中调用 bash

标签 python multithreading bash

我需要从我的 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')

关于python - 在线程中调用 bash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49191379/

相关文章:

bash - sed 不写入文件

python - 多维 numpy 矩阵的旋转和翻转

python - 引发似乎来自调用者的异常

java - ArrayList 在不同线程中为空

bash - cd 到由管道命令确定的目录

linux - Shell 表示法 : find . -type f -exec file '{}'\;

python - 在 if 语句下将两个 for 循环合并在一起

python 如何查找哪些父类定义了子对象的方法

C++,如何在进程或线程之间共享数据

java - 我可以相信操作系统调度线程 "optimal"(并行化)