Launch a shell command with in a python script, wait for the termination and return to the script(在 python 脚本中启动 shell 命令,等待终止并返回脚本)
问题描述
我有一个 python 脚本,它必须为目录中的每个文件启动一个 shell 命令:
I've a python script that has to launch a shell command for every file in a dir:
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
这对于第一个文件很好,但是在myscript"命令结束后,执行停止并且不会返回到 python 脚本.
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
我该怎么办?我必须在 调用 os.execlp() 之前 fork() 吗?
How can I do? Do I have to fork() before calling os.execlp()?
推荐答案
subprocess:
subprocess模块允许您生成新进程,连接到他们的输入/输出/错误管道,并获取它们的返回码.
subprocess: The
subprocessmodule allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
http://docs.python.org/library/subprocess.html
用法:
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
这篇关于在 python 脚本中启动 shell 命令,等待终止并返回脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 python 脚本中启动 shell 命令,等待终止并返回脚本
基础教程推荐
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
