os.system
In [6]: import os
In [7]: r = os.system('curl ifconfig.me')
139.226.51.147
In [8]: print r
0
os.system
的返回值是执行后的退出状态码,获取不到运行命令的输出结果
os.popen
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
对象,可以对这个对象默认进行读操作。
commands
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
方法返回的直接是字符串
subprocess
In [28]: import subprocess
In [29]: subprocess.call(['curl', 'ifconfig.me'])
139.226.51.147
Out[29]: 0