使用python脚本启动shell命令,等待终止并返回脚本 [英] Launch a shell command with in a python script, wait for the termination and return to the script

查看:468
本文介绍了使用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.

我该怎么办?我必须在calling os.execlp()之前先fork()吗?

How can I do? Do I have to fork() before calling os.execlp()?

推荐答案

子进程:subprocess模块 允许您产生新的流程, 连接到他们的输入/输出/错误 管道,并获取其返回码.

subprocess: The subprocess module 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命令,等待终止并返回脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆