博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python系统命令操作
阅读量:7040 次
发布时间:2019-06-28

本文共 3152 字,大约阅读时间需要 10 分钟。

系统命令

1、call

执行命令,返回状态码

ret = subprocess.call(['ls', '-l'], shell=False)      ret = subprocess.call('ls -l', shell=True)

2、check_call

执行命令,如果执行状态码是0,则返回0,否则抛异常

subprocess.check_call(["ls", "-l"])  subprocess.check_call("exit 1", shell=True)

3、check_output

执行命令,如果状态是0,则返回执行结果,否则抛异常

subprocess.check_output(["echo", "hello world !"])      subprocess.check_output(["exit 1", shell=True])

subprocess.Popen(....)

用于执行复杂的系统命令

参数:

 
    • args:shell命令,可以是字符串或者序列类型(如:list,元组)
    • bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
    • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
    • preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
    • close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
      所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
    • shell:同上
    • cwd:用于设置子进程的当前目录
    • env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
    • universal_newlines:不同系统的换行符不同,True -> 同意使用 \n
    • startupinfo与createionflags只在windows下有效
      将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
 

所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin,stdout,stderr)

案例:import subprocessret1 = subprocess.Popen(["mkdir", "t1"])ret2 = subprocess.Popen("mkdir t2", shell=True)

终端输入的命令分为两种:

输入即可得到输出,如:ifconfig

输入进行某环境,依赖在输入,如:python

import subprocess      obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev')
import subprocess      obj = subprocess.Popen(["python"], stdin=dubprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, universal_newlines=True)      obj.stdin.write("print(1)\n")      obj.stdin.write("print(2)")      obj.stdin.close()            cmd_out = obj.stdout.read()      obj.stdout.close()      cmd_error = obj.stderr.read()      obj.stderr.close()            print(cmd_out)      print(cmd_error)
View Code
import subprocess            obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)      obj.stdin.write("print(1)\n")      obj.stdin.write("print(2)")            out_error_list = obj.communicate()      print(out_error_list)
View Code
import subprocess            obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)      out_error_list = obj.communicate('print("hello")')      print(out_error_list)
View Code

 

 

执行python代码,调用系统命令, 怎么得到返回值

import osimport subprocessobj = subprocess.Popen("ifconfig", shell=True, stdout = subprocess.PIPE)print("===================")print(obj.stdout.read().decode("utf-8"))print("===================")

 

看自己需求,可以进行修改

import subprocessdef local_exec_shell_command(shell_command, is_shell=True):    """    @:param shell_comamnd    @:return exec_result(True or False) _stdout _stderr    """    try:        process = subprocess.Popen(            shell_command,            shell=is_shell,            stdout=subprocess.PIPE,            stderr=subprocess.PIPE        )        _stdout, _stderr = process.communicate()        if process.returncode != 0:            return False, _stdout, _stderr        return True, _stdout, _stderr    except Exception as e:        return False, '', str(e)if __name__ == '__main__':    data = local_exec_shell_command("ifconfig")    print(data)

 

转载地址:http://fsxal.baihongyu.com/

你可能感兴趣的文章
ORACLE数据库事务隔离级别介绍
查看>>
DHCP服务和http服务
查看>>
bitnami 使用记录
查看>>
ActiveMQ(02):JMS基本概念和模型
查看>>
理解 Delphi 的类(十一) - 深入类中的方法[8] - 抽象方法与抽象类
查看>>
Python Flask+Bootstrap+Jinja2 构建轻量级企业内部系统平台框架
查看>>
Xen 和 KVM 下如何关闭 virbr0
查看>>
Hyperledger Fabric启用CouchDB为状态数据库
查看>>
MySQL 5.7.5: GTID_EXECUTED系统表(下)
查看>>
使用Microsoft Azure Backup Server实现应用程序工作负载的保护(1)
查看>>
MusicXML 3.0 (22) - 强、弱、渐强、渐弱、渐快、渐慢
查看>>
Android5.0样式解析图
查看>>
VUE在线编辑插件vue2-ace-editor
查看>>
Oracle数据库频繁DELETE导致表碎片案例
查看>>
Objective-C 之 @property和@synthesize
查看>>
策略模式
查看>>
细数十个最令人头疼的性能瓶颈
查看>>
Servlet的使用
查看>>
Git实用命令速记
查看>>
构建故障分析平台采用python实现抓包分析数据包
查看>>