在 python 脚本中启动 shell 命令,等待终止并返回到脚本
我有一个 python 脚本,必须为目录中的每个文件启动 shell 命令:
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
这对于第一个文件来说效果很好,但是在“myscript”命令结束后,执行停止并且不会返回到 python 脚本。
我怎样才能做到这一点? 在调用 os.execlp()
之前是否必须fork()
?
I have 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)
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.
How can I do this? Do I have to fork()
before calling os.execlp()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
http://docs.python.org/library/subprocess.html
用法:
http://docs.python.org/library/subprocess.html
Usage:
您可以使用
subprocess.Popen
。 有几种方法可以做到这一点:或者,如果您不关心外部程序实际做什么:
You can use
subprocess.Popen
. There's a few ways to do it:Or, if you don't care what the external program actually does:
subprocess 模块自 2008 年以来一直在发展。特别是
check_call
和check_output
使简单的子流程工作变得更加容易。check_*
系列函数很不错,如果出现问题,它们会引发异常。myscript
生成的任何输出都将显示为您的进程生成了输出(从技术上讲,myscript
和您的 python 脚本共享相同的标准输出)。 有几种方法可以避免这种情况。check_call( [ 'myscript', f ], stdout=subprocess.PIPE )
stdout 将被抑制(如果
myscript
产生超过 4k 的输出,请注意)。 除非您添加选项stderr=subprocess.PIPE
,否则 stderr 仍会显示。check_output([ 'myscript', f ] )
check_output
将标准输出作为字符串返回,因此不会显示。 除非添加选项stderr=subprocess.STDOUT
,否则仍会显示 stderr。The subprocess module has come along way since 2008. In particular
check_call
andcheck_output
make simple subprocess stuff even easier. Thecheck_*
family of functions are nice it that they raise an exception if something goes wrong.Any output generated by
myscript
will display as though your process produced the output (technicallymyscript
and your python script share the same stdout). There are a couple of ways to avoid this.check_call( [ 'myscript', f ], stdout=subprocess.PIPE )
The stdout will be supressed (beware if
myscript
produces more that 4k of output). stderr will still be shown unless you add the optionstderr=subprocess.PIPE
.check_output( [ 'myscript', f ] )
check_output
returns the stdout as a string so it isnt shown. stderr is still shown unless you add the optionstderr=subprocess.STDOUT
.os.exec*()
函数将当前程序替换为新程序。 当这个程序结束时,你的进程也会结束。 您可能需要os.system()
。The
os.exec*()
functions replace the current programm with the new one. When this programm ends so does your process. You probably wantos.system()
.使用生成
use spawn
我使用 os.system
I use os.system
这对我来说很好!
shell_command = “ls -l”
subprocess.call(shell_command.split())
this worked for me fine!
shell_command = "ls -l"
subprocess.call(shell_command.split())