python执行shell命令的几种方法
test.py代码如下:
import sys
print(sys.argv)
slice = sys.argv[1]
print(slice)
os.system(“command”)
import os
os.system(f'python test.py city')
0
os.system(f'chdir')
0
os.popen(“command”)方法
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
import subprocess
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
exe_sh('chdir')
执行成功
D:\ThereIsNoEndToLearning\Zzz-Temp
!chdir
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 于南京市江宁区九龙湖