Python 调用 Shell脚本的方法
1.os模块的popen方法
通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。
>>> os.popen('date -u |wc') <open file 'date -u |wc', mode 'r' at 0x7f9539eb34b0> >>> os.popen('date -u |wc').read() ' 1 6 43 '
2.利用commands模块
这个模块有个非常好用的方法可以直接读取程序执行的返回值
通过 commands.getstatusoutput() 一个方法就可以获得到返回值和输出
>>> import commands >>> commands.getstatusoutput('ls /bin/ls') (0, '/bin/ls') >>> commands.getstatusoutput('cat /bin/junk') (256, 'cat: /bin/junk: No such file or directory') >>> commands.getstatusoutput('/bin/junk') (256, 'sh: /bin/junk: not found') >>> commands.getoutput('ls /bin/ls') '/bin/ls' >>> commands.getstatus('/bin/ls') '-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
3.利用subprocess模块
subprocess模块用来启动可终止其它程序,创建多个进程.想要shell中运行其它程序并获取它的输出,可以使用check_output()方法,它接受一个命令和参数列表
>>> subprocess.check_output(["echo", "Hello World!"]) 'Hello World! ' >>> ret = subprocess.check_output(['date','-u']) >>> ret '2016xe5xb9xb4 05xe6x9cx88 20xe6x97xa5 xe6x98x9fxe6x9cx9fxe4xbax94 09:48:44 UTC '
本文转载自:https://blog.csdn.net/u010786109/article/details/51463598