【python】python运行exe,并获取exe的output

来源:互联网 发布:麻将源码 编辑:程序博客网 时间:2024/04/20 00:35

想要在python实现人眼的定位,c++代码在此:

基础学习笔记之opencv(1):opencv中facedetect例子浅析,感谢!

说主题。

python中调用exe是很简单的:

os.system(command)

就可以了,其中command可以是像date这样的系统自带(这里我用的是windows)的exe,也可以是自己编写的需要参数输入的exe,比如我这里有一个比较复杂的

os.system('D:\OpenCV_Workspace\eye_cascadeClassifier\Debug\eye_cascadeClassifier.exeD:\OpenCV_Workspace\eye_cascadeClassifier\Debug\test.jpg')
结果一闪而过

只留下一个shell中的 0 ,证明这个程序被正确运行了(我以为)。

但是我想要的是能够得到exe输出到cmd中的信息,也就是exe的output。

首先搜索到了stackoverflow上的两个提问:

How to get output of exe in python script?

回答是这样的:

To call an external program from Python, use thesubprocess module.

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

An example from the doc (output is a file object that provides output from the child process.):

output = subprocess.Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

A concrete example, usingcmd, the Windows command line interpreter with 2 arguments:

>>> p1 = subprocess.Popen(["cmd", "/C", "date"],stdout=subprocess.PIPE)>>> p1.communicate()[0]'The current date is: Tue 04/14/2009 \r\nEnter the new date: (mm-dd-yy) '>>>

我把人家的这个代码换成我自己的
p1 = subprocess.Popen(["cmd", "/C", command_str],stdout=subprocess.PIPE)
其中command_str是上面的 'D:\OpenCV_Workspace\eye_cascadeClassifier\Debug\eye_cascadeClassifier.exe D:\OpenCV_Workspace\eye_cascadeClassifier\Debug\test.jpg'
结果,悲剧了,出来一个空字符串...

>>> p1 = subprocess.Popen(["cmd", "/C", command_str],stdout=subprocess.PIPE)>>> p1.communicate()[0]''

看另一个:

How do I get all of the output from my .exe using subprocess and Popen?

人家的回答太多,我不粘了。

按照人家的回答第一条:

>>> output = qx(cmd)>>> print output
擦,貌似还是输出一个空的字符串,唉。


哥这次彻底不爽了,于是拿出看家本领,控制变量法...,试了半天,发现,其实这个程序一直没有被正确运行过!!!包括之前用os.system的时候!输出0只是说明程序执行到了最后一步return 0;程序根本没有加载到图片,也就是说命令字符串cmd前面的一半:

D:\OpenCV_Workspace\eye_cascadeClassifier\Debug\eye_cascadeClassifier.exe的时候,找到了这个程序;
后面的一半:
D:\OpenCV_Workspace\eye_cascadeClassifier\Debug\test.jpg,找不到这个图片了...
这是怎么回事,我不知道,我只知道window中表示路径的反斜杠\在py中要使用\\或者在字符串前加r,可是我还以为这里只需要一个字符串放到cmd里面执行不就行了么,没想到前一半行,后一半不行...被坑了。于是老老实实在前面加r:
r'D:\OpenCV_Workspace\eye_cascadeClassifier\Debug\eye_cascadeClassifier.exe D:\OpenCV_Workspace\eye_cascadeClassifier\Debug\201228018629075.jpg'
r'D:\OpenCV_Workspace\eye_cascadeClassifier\Debug\eye_cascadeClassifier.exe'+' '+r'D:\OpenCV_Workspace\eye_cascadeClassifier\Debug\201228018629075.jpg'
以上这两种都可以。
等等,为什么我那么久才发现是资源没有载入!
程序中有一个
cerr << "WARNING: Could not load classifier cascade for nested objects" << endl;
我是指望这个cerr能够做点什么的,事实如下:
c++中的代码:
cout<<"i am cout"<<endl;
printf("i am printf\n");
cerr << "i am cerr" << endl;

输出:

>>> i am couti am printf
cerr居然不输出!

看看百度百科:http://baike.baidu.com/view/2254717.htm,罢了。


然后突然又找到一个比较系统的subprocess,不过我基本没看明白,头大

[转载]Python模块学习 ---- subprocess 创建子进程

这次教训如下:
1.不要老怀疑别人的问题
2.r的重要性
3.cerr
4.基础需要更扎实
5.csdn这个编辑器怎么这么难用!!!
原创粉丝点击