网上文章一般都是用的这个方法
p = Popen(cmd,shell=True,stdout=PIPE, stderr=PIPE)
然后 p.poll() 可以获得状态,如果不是None,就是完成了。
不知道是不是windows的问题,运行dir这样的没事,如果运行ffmpeg就不行了,一直是None,无法获得状态。
最后用了比较原始的办法,开个线程运行cmd命令,主线程验证是否完成和是否超时。
命令行线程:
class CommandThread(threading.Thread):
def __init__(self,cmd):
threading.Thread.__init__(self)
self.cmd=cmd
self.result='';
self.over=0;
pass
def run(self):
try:
strresult=subprocess.getoutput(self.cmd)
self.result=strresult
self.over=1
return
except Exception as e:
print("cmd err")
self.over=1
pass
主线程:
@staticmethod
def cmd(command, timeout=10):
try:
cmdThread=CommandThread(command);
cmdThread.start();
t_beginning = time.time()
seconds_passed = 0
while True:
if(cmdThread.over==1):
str=cmdThread.result;
break;
seconds_passed = time.time() - t_beginning
if timeout and seconds_passed > timeout:
print("time out le;")
break;
time.sleep(0.1)
# LogUtil.log(str)
return str
except Exception as e:
print(e)
return None
就是这个样子,因为sleep可能会有0.1的延迟,但是能解决ffmpeg命令行莫名其妙卡死的问题。