Python 脚本执行另一个脚本并在第二个脚本完成其工作后恢复
有没有办法检查子进程是否完成其工作?我的 python 脚本从 cmd 执行 123.exe。 123.exe 然后执行一些操作,最后将 1 或 0 写入 txt 文件。然后,Python 脚本读取 txt 文件,如果为“1”则继续作业,如果为“0”则停止。目前我能想到的就是让 python 脚本休眠一分钟。这样,123.exe 肯定已将 1 或 0 写入 txt 文件中。这种认识非常简单,但同时也是愚蠢的。
所以我的问题是,有没有办法在不需要超时的情况下处理这个问题?一种让 python 脚本等待 123.exe 停止的方法?
Is there a way to check if a subprocess has finished its job? My python script executes an 123.exe from cmd. 123.exe then does some things and in the end it writes 1 or 0 to a txt file. Python script then reads the txt file and continues with the job if '1' and stops if '0'. At the moment all that I can think of, is to put the python script to sleep for a minute. That way the 123.exe has most certainly written 1 or 0 into the txt file. This realization is very simple but at the same time stupid.
So my question is, is there a way to deal with this problem without the need for timeout? A way to make the python script to wait til the 123.exe stops?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用:
这将执行命令,等待它完成,然后将其返回代码放入 retcode 中(这样,如果命令返回正确的值,您还可以避免检查输出状态文件的需要)返回码)。
如果您需要手动实例化
subprocess.Popen
,请执行(然后检查
Popen.returncode
)。Use:
This will execute the command, wait until it finishes, and you get its return code into
retcode
(this way you could also avoid the need of checking the output status file, if the command returns a proper return code).If you need to instantiate manually the
subprocess.Popen
, then go for(and then check
Popen.returncode
).我会使用
call()
subprocess 模块的简写。从文档中:它应该这样工作:
当然您不会使用
retcode
,但您的脚本无论如何都会挂起,直到 123.exe 终止。I would use the
call()
shorthand from the subprocess module. From the documentation:It should work this way:
of course you won't use the
retcode
, but your script will anyhow hang until the 123.exe has terminated.试试这个:
这将等到该过程完成并且您的脚本将从这里继续。
Try this:
This will wait until the process is done and your script will continue from here.