PythonNote038---python执行shell命令
原创
©著作权归作者所有:来自51CTO博客作者维格堂406小队的原创作品,请联系作者获取转载授权,否则将追究法律责任
Intro
python执行shell命令的几种方法
test.py代码如下:
import sys
print(sys.argv)
slice = sys.argv[1]
print(slice)
os
os.system(“command”)
os.system(f'python test.py city')
os.popen(“command”)方法
- 返回的是 file read 的对象,对其进行读取 read() 的操作
- 成功正常打印输出内容,失败啥都没有
f=os.popen(f'python test.py city0') # 返回的是一个文件对象
print(f.read())
f.close()
['test.py', 'city0']
city0
f=os.popen('chdir') # 返回的是一个文件对象
print(f.read())
f.close()
D:\ThereIsNoEndToLearning\Zzz-Temp
subprocess.Popen
- 可以获取执行成功或者报错的标识
- 能够得到输出信息,但是只能等所有代码执行完,才能获取中间的输出结果
def exe_sh(cmd):
# cmd = f'/opt/conda/bin/python test.py city0'
res = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding='utf8',
text=True)
# stderr = res.stderr.read().decode("gbk")
# stdout = res.stdout.read().decode("utf8") # 获取标准输出
stdout, stderr = res.communicate()
if res.returncode == 0:
print('执行成功')
print(stdout)
else:
print('执行失败')
print(stderr)
exe_sh(f'python test.py city0')
执行成功
['test.py', 'city0']
city0
执行成功
D:\ThereIsNoEndToLearning\Zzz-Temp
jupyter magic
D:\ThereIsNoEndToLearning\Zzz-Temp
如果用jupyter执行且是执行python脚本,优先选这个方法,边执行边打印输出
for i in ['city0','city2']:
%run test.py $i
['test.py', 'city0']
city0
['test.py', 'city2']
city2
2022-08-26 于南京市江宁区九龙湖