Python作为一门脚本语言,有时候需要与shell命令交互式使用,在Python中提供了很多的方法可以调用并执行shell脚本,本文介绍几个简单的方法。
Python怎么运行shell脚本
一、os.system(“command”)
1 2 3 | import os
print (os.system( "touch a.txt" ))
print (os.system( "ls -a" ))
|
第2行会返回一个0,表示执行成功了,然后在当前文件夹之下创建了一个新的a.txt文件
第3行也会返回一个0,也就是说这个命令执行的结果没有办法查看,即system函数不返回shell命令执行的结果。
二、os.popen("command")方法
os.popen() 返回的是一个文件对象
1 2 3 4 5 6 7 8 9 | import os
f=os.popen( "ls -l" ) # 返回的是一个文件对象
print (f.read()) # 通过文件的read()读取所返回的内容
'' '
total 4
-rw-rw-r-- 1 tengjian tengjian 0 11月 5 09:32 a.txt
-rw-rw-r-- 1 tengjian tengjian 81 11月 5 09:32 python_shell.py
'' '
|
对于那些没有返回指的shell命令,我依然也可以使用popen()方法,如下:
1 2 3 4 5 | import os
f=os.popen( "touch b.txt" ) # 创建一个文件
# f=os.popen( "mkdir newdir" ) # 创建一个新的文件夹
print (f.read()) # 无返回值
|
总结:
对于有返回值的shell命令,建议使用 os.popen()
对于没有返回值的shell命令,建议使用 os.system()
更多技术请关注Python视频教程。