python执行命令行

Posted xiejunna

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python执行命令行相关的知识,希望对你有一定的参考价值。

我这里用到了subprocess.Popen()和subprocess.run()
执行ping命令示例如下:

# -*- coding: utf-8 -*-
import os
import subprocess
import re
import sys


def get_ping(ip, count):
    platform = sys.platform

    if "win" in platform:
    	command = 'ping -n %s' % count + " %s" % ip
        p = subprocess.Popen(command,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, shell=True)
        out = p.stdout.read().decode('gbk')
        # regex = r'时间=(.+?)ms'

    elif "linux" in platform:
    	command = 'ping -c %s' % count + " %s" % ip
        p = subprocess.Popen([command],
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, shell=True)
        out = p.stdout.read().decode('utf-8')
        # regex = r'time=(.+?)ms'

    print(out)
    


if __name__ == '__main__':
    ip = 'www.baidu.com'
    count = 4
    command = 'ping -n %s' % count + " %s" % ip
    print(command)
    
    proc = subprocess.run(command, shell=True, stdout=subprocess.PIPE)
    print(proc.stdout.decode("gbk"))

    # p = subprocess.Popen(['D:', 'cd /home/dev/train_work/ymtcv/', './start_train.sh', 'terminal', '10'], stdout=subprocess.PIPE, shell=True)

    print('1==========================================1')

    p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    print(p.stdout.read().decode("gbk"))

    print('2==========================================2')

    get_ping('www.baidu.com' , 4)

    print('3==========================================3')







以上是关于python执行命令行的主要内容,如果未能解决你的问题,请参考以下文章

Python 命令行参数以及代码编译发布为可执行文件

Python 命令行参数以及代码编译发布为可执行文件

如何使用python 执行命令行传入的代码

python执行命令行调试工具pdb

python调试:pdb基本用法(转)

Python项目命令行执行无法找到Module(ModuleNotFoundError)