• PythonNote038---python执行shell命令


    Intro

    python执行shell命令的几种方法

    test.py代码如下:

    import sys
    print(sys.argv)
    slice = sys.argv[1]
    print(slice)
    
    • 1
    • 2
    • 3
    • 4

    os

    os.system(“command”)

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

    os.popen(“command”)方法

    • 返回的是 file read 的对象,对其进行读取 read() 的操作
    • 成功正常打印输出内容,失败啥都没有
    f=os.popen(f'python test.py city0')  # 返回的是一个文件对象
    print(f.read())      
    f.close()
    
    • 1
    • 2
    • 3
    ['test.py', 'city0']
    city0
    
    • 1
    • 2
    f=os.popen('chdir')  # 返回的是一个文件对象
    print(f.read())      
    f.close()
    
    • 1
    • 2
    • 3
    D:\ThereIsNoEndToLearning\Zzz-Temp
    
    • 1

    subprocess.Popen

    • 可以获取执行成功或者报错的标识
    • 能够得到输出信息,但是只能等所有代码执行完,才能获取中间的输出结果
    import subprocess
    
    • 1
    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    exe_sh(f'python test.py city0')
    
    • 1
    执行成功
    ['test.py', 'city0']
    city0
    
    • 1
    • 2
    • 3
    exe_sh('chdir')
    
    • 1
    执行成功
    D:\ThereIsNoEndToLearning\Zzz-Temp
    
    • 1
    • 2

    jupyter magic

    !chdir
    
    • 1
    D:\ThereIsNoEndToLearning\Zzz-Temp
    
    • 1

    如果用jupyter执行且是执行python脚本,优先选这个方法,边执行边打印输出

    for i in ['city0','city2']:
        %run test.py $i
    
    • 1
    • 2
    ['test.py', 'city0']
    city0
    ['test.py', 'city2']
    city2
    
    • 1
    • 2
    • 3
    • 4

                                            2022-08-26 于南京市江宁区九龙湖

  • 相关阅读:
    2022/7/27 考试总结
    rpc网络
    Linux环境基础开发工具使用(下)
    前端面试宝典React篇12 React 的渲染异常会造成什么后果?
    独家 | 2022 年十项突破性技术
    UNITY零基础学习 month1 day16
    数据结构:树
    图像特征提取算法之Haar特征原理(一)
    从1开始的Matlab(快速入门)
    类型多样的石膏PBR多通道贴图素材,速来收藏!
  • 原文地址:https://blog.csdn.net/wendaomudong_l2d4/article/details/126548163