Python中调用SHELL的几种方式

2018-09-26  本文已影响0人  octocat
In [6]: import os

In [7]: r = os.system('curl ifconfig.me')
139.226.51.147

In [8]: print r
0

os.system的返回值是执行后的退出状态码,获取不到运行命令的输出结果

In [7]: r = os.popen('curl --silent ifconfig.me')

In [8]: r
Out[8]: <open file 'curl --silent ifconfig.me', mode 'r' at 0x10f2f6c00>

In [9]: r.read()
Out[9]: '139.226.51.147\n'

os.popen返回的是一个file对象,可以对这个对象默认进行读操作。

In [17]: import commands

In [18]: commands.getstatusoutput('curl --silent ifconfig.me')
Out[18]: (0, '139.226.51.147')

In [19]: commands.getoutput('curl --silent ifconfig.me')
Out[19]: '139.226.51.147'

commands.getoutput方法返回的直接是字符串

In [28]: import subprocess

In [29]: subprocess.call(['curl', 'ifconfig.me'])
139.226.51.147
Out[29]: 0
上一篇 下一篇

猜你喜欢

热点阅读