Python popen 命令。等待命令完成
我有一个脚本,可以使用 popen shell 命令启动。 问题是脚本不会等到 popen 命令完成并立即继续。
om_points = os.popen(command, "w")
.....
如何告诉我的 Python 脚本等待 shell 命令完成?
I have a script where I launch with popen a shell command.
The problem is that the script doesn't wait until that popen command is finished and go continues right away.
om_points = os.popen(command, "w")
.....
How can I tell to my Python script to wait until the shell command has finished?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
wait() 对我来说效果很好。子进程p1、p2和p3同时执行。因此,所有过程在3秒后完成。
wait() works fine for me. The subprocesses p1, p2 and p3 are executed at the same. Therefore, all processes are done after 3 seconds.
我认为 process.communicate() 适合小尺寸的输出。对于更大的输出,这不是最好的方法。
I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.
根据您想要如何运行脚本,您有两种选择。如果您希望命令在执行时阻塞并且不执行任何操作,则可以使用
subprocess.call
。如果您想在执行时执行操作或将内容输入到
stdin
中,则可以在popen
调用之后使用communicate
。如文档中所述,
wait
可能会死锁,因此建议进行通信。Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use
subprocess.call
.If you want to do things while it is executing or feed things into
stdin
, you can usecommunicate
after thepopen
call.As stated in the documentation,
wait
can deadlock, so communicate is advisable.您可以使用
subprocess
来实现这一点。You can you use
subprocess
to achieve this.通过执行以下操作,强制
popen
在读取所有输出之前不继续:Force
popen
to not continue until all output is read by doing:让您尝试传递的命令为,
然后将其隐藏为一条语句,
现在Python将等待命令行的输出,以便将其分配给变量
t
。Let the command you are trying to pass be
then you covert it to a statement
now the python will be waiting for the output from the commandline so that it could be assigned to the variable
t
.您正在寻找的是
wait
方法。What you are looking for is the
wait
method.