我正在尝试按顺序打开和关闭应用程序。但问题是应用程序正在打开,但要进入下一行,即该应用程序的结束行,我必须手动关闭应用程序。
import os
os.system("scad3 file.txt")
os.system("TASKKILL /PID scad3.exe /T")
scad3是我希望运行的应用程序,但要进入下一行,即taskkilling行,我必须手动关闭窗口 请让我知道有什么办法可以解决吗?
非常感谢你
答案 0 :(得分:4)
我猜os.system是一个阻塞调用。尝试在python中使用Popen对象: -
import subprocess
p = subprocess.Popen("notepad.exe")
p.terminate()
参考:https://docs.python.org/2/library/subprocess.html#popen-objects
答案 1 :(得分:1)
您可以尝试使用popen执行命令然后等待给定时间并尝试获取结果或者如果尚未完成则终止子进程。
import subprocess
def get_array_from_cmd_str(cmd_str):
cmd_str_parts = cmd_str.split(" ")
return [cmd_part for cmd_part in cmd_str_parts]
def run_command_str(command):
p = subprocess.Popen(get_array_from_cmd_str(command),
stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0]
resp = {'out': p[0],
'err': p[1]}
return resp
运行命令以这种方式使用上面的“run_command_str”函数:
import time
cmd = "scad3 file.txt"
cmd_out = run_command_str(cmd)
expected_execution_time = 5
time.sleep(expected_execution_time)
if cmd_out['err'] != '':
pass # handle error here
现在,如果你的程序没有自动关闭,你可以使用this thread中描述的方法修改手动杀死它的方法。
(未在Windows上测试的示例)
编辑:根据有价值的评论修改代码。示例进行阻止调用,但不解决问题;使用其他的。