python代码调用linux命令

什么os,commands别用了

原来使用os、commands执行linux命令的时候存在的问题:

  1. 进程卡死,需要等命令执行完毕,才能继续往下执行
  2. 不能实时显示命令的进度条,比如执行:wget http://***.tar.gz。

后来询问了张老师:subprocess   翻译叫:子进程      ?  多线程和多进程的问题? 和进程有啥关系?

学习:subprocess包中定义有数个创建子进程的函数,这些函数分别以不同的方式创建子进程。

 subprocess.run()     2.7中没有这个方法   返回:命令执行结果  和  一个类 CompletedProcess(命令,状态码)

>>> import subprocess
>>> a = subprocess.run('ls')   这样终端只会打印出执行命令结果
0.10.4性能测试报告.docx cert_问题复现 

>>> a          
CompletedProcess(args='ls', returncode=0)      #returncode=0 表示执行成功。

>>> subprocess.run('ls')    如果直接写subprocess.run('ls')  那么直接在终端打出CompletedProcess(args='ls', returncode=0) 和 执行命令结果
0.10.4性能测试报告.docx cert_问题复现
CompletedProcess(args='ls', returncode=0)
>>> subprocess.run('ls -al',shell=True)    # 需要交给Linux shell自己解析,则:传入命令字符串,shell=True

---------

执行错误

>>> subprocess.run('ll',shell=True)   #mac不支持ll
/bin/sh: ll: command not found
CompletedProcess(args='ll', returncode=127)  #returncode != 0 就是执行失败

>>> subprocess.run('ll')   #不加shell=True直接报错   所以还是加上shell=True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 472, in run
with Popen(*popenargs, **kwargs) as process:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 1522, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'll': 'll'

subprocess.call()    返回: 命令执行结果  和  状态码 

>>> a = subprocess.call('ls',shell=True)
0.10.4性能测试报告.docx cert_问题复现
>>> a
0

subprocess.check_call()   检查,linux报错,python程序报错,加了shell=True 也报错

>>> subprocess.check_call('ll',shell=True)   #加了shell 依旧报错
/bin/sh: ll: command not found
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 347, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'll' returned non-zero exit status 127.
>>> subprocess.call('ll',shell=True)    #call 加了shell 就不会报错
/bin/sh: ll: command not found
127

--------以上的方法都对下面的封装

subprocess.Popen()

# -*- coding:utf-8 -*-
str = 'certhugegraph.traversal().V(1).bothE().limit(1).count()'

import subprocess

# return_code = subprocess.call('wget ')
a = subprocess.Popen('ls',shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)    #std*** 把执行结果放到std***  然后通过read读取
print(a)    #返回的是对象 <subprocess.Popen object at 0x10a6dc290>
print(a.pid)  # 执行的进程id
print(a.stdout.read())  #标准输出 就是正确的结果输出在这里
print(a.stderr.read())  # 为空,因为已经有正确的结果了
原文地址:https://www.cnblogs.com/tarzen213/p/12206726.html