PythonNote038---python执行shell命令

Intro

python执行shell命令的几种方法

test.py代码如下:

import sys
print(sys.argv)
slice = sys.argv[1]
print(slice)

os

os.system(“command”)

  • 得不到输出
  • 成功返回0,失败返回其他
import os
os.system(f'python test.py city')
0
os.system(f'chdir')
0

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

  • 可以获取执行成功或者报错的标识
  • 能够得到输出信息,但是只能等所有代码执行完,才能获取中间的输出结果
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

jupyter magic

!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 于南京市江宁区九龙湖

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值