1.调用系统命令
import os
1.1打印所有文件状态信息和‘0’其中0表示执行成功非0表示执行失败
1.2 把执行的命令赋值给a 此时a只储存执行状态
1.3打印 'os.popen(''dir)'只会显示储存所有状态信息的地址,此时可以把它赋值给一个变量用‘read()’方法去读出来
2.subprocess.run:
2.1
a = subprocess.run(['dir','-S'], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, check= True, encoding='GBK')
print(a.stdout,'
', a.stderr)
# stderr接受异常输出
#stdout接受标准输出
#check 如果有异常直接报错
2.2
a = subprocess.run('dir -S |dir 文件名字', stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, encoding='GBK')
print(a.stdout,'
', a.stderr)
#此操作不能以列表形式给‘subprocess.run'解析,而是把‘'dir -S |dir 文件名字’这个管道命令给shell直接处理帅选到指定的‘文件名字’ 此时 shelli= True必须存在
3 subprocess.call:
#只返回执行状态0或者非零
a = subprocess.call(['dir', '-S '])
'0'
#执行命令,如果为0就正常返回,否则抛出异常
a = subprocess.check_call(['dir', '-S '])
'0'
#接受str命令 返回元祖形式, 第一个是执行状态, 第二个执行结果
a = subprocess.getstatusoutput('dir /luffy/dir')
('0', '/luffy/dir')
#接受str命令只返回结果
a = subprocess.getoutput('dir /luffy/dir')
('/luffy/dir')
#执行命令并且返回结果 注意是返回结果,不是打印, 返回给a 打印a才会显示结果,且只返回正确的输出
a.subprocess.check_output(['dir', '-S '])
print(a)
4,subprocess.Popen
1.
#run和 Pope的区别是run是只有先主程序执行完才执行后面的shell脚本,而Popen是shell脚本和主程序同时执行,相当于由开了一个新的进程
a = subprocess.run('sleep 10', shell=True, stdout=subprocess.PIPE, encoding='utf-8')
s = subprocess.Popen('sleep 10', shell=True, stdout=subprocess.PIPE, encoding='utf-8')