python执行linux命令

2017-07-11 14:59:41

blog

1.对于一些简单的命令,我们可以直接使用

print(os.system('ls'))

'''
Output:

__pycache__
class
compile_.py
compile_fun_.py
daily_python
decortor2.py
decotr.py
dector1.py
dector3.py
fucture.py
function_generator.py
leap_year.py
mult.py
mux_thread.py
'''

2.获取输出.

f = os.popen('ls')
print(f.readlines())

['__pycache__\n', 'class\n', 'compile_.py\n', 'compile_fun_.py\n']

3.你可以使用subprocess实现同样的目的

res = subprocess.call(('cat','/Users/fiz/Desktop/1.txt'))
print(res)
#output: dgdigdigdhighighi,0  

4.输出到文件中

with open("stdout.txt","wb") as out, open("stderr.txt","wb") as err:
     subprocess.Popen("ls",stdout=out,stderr=err)

5.run

subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)

FIZLIN
514 声望8 粉丝

跟我走吧,天亮就出发


引用和评论

0 条评论