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())  # 為空,因為已經有正確的結果了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM