python执行外部程序的常用方法小结

WBOY
Release: 2016-06-10 15:17:02
Original
1356 people have browsed it

本文实例总结了python执行外部程序的常用方法。分享给大家供大家参考。具体分析如下:

在python中我们可以通过下面的方法直接调用系统命令或者外部程序,使用方便

1、os模块的execl方法

Python的execl系统方法同Unix的exec系统调用是一致的。这些方法适用于在子进程中调用外部程序的情况,因为外部程序会替换当前进程的代码,不会返回。
也就是说,这个shell进程被占领,将执行第一个execl的命令程序而不再返回。

2、使用os模块的system方法

system方法会创建子进程运行外部程序,方法只返回外部程序的运行结果。这个方法比较适用于外部程序没有输出结果的情况。比如在Ubuntu下,使用下面命令在桌面上显示一条提示信息。
根据我的实验,用system方法调用的进程正常结束返回0,异常结束返回非0,而不取决于进程主函数的返回值。

3、使用os模块的popen方法

当需要得到外部程序的输出结果时,本方法非常有用。比如使用urllib调用Web API时,需要对得到的数据进行处理。一个使用例子如下:

cmd = "ssh search47c.cm2 \"" + query + "\""
#print cmd + "<br>"
output = os.popen(cmd)
#对特殊字符进行转义
temp1 = output.read().replace('<','<')
temp2 = temp1.replace('>', ">")
temp3 = temp2.replace('\n', "<br>")
print temp3.replace('/', "&#47")
Copy after login

4、使用commands模块的getoutput方法(没用过)

这种方法同popend的区别在于popen返回的是一个文件句柄,而本方法将外部程序的输出结果当作字符串返回,很多情况下用起来要更方便些。

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!