亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

運行shell命令并捕獲輸出

運行shell命令并捕獲輸出

收到一只叮咚 2019-06-01 10:27:55
運行shell命令并捕獲輸出我想編寫一個函數,它將執行shell命令并返回其輸出。如一串不管是錯誤還是成功的信息。我只想得到與命令行相同的結果。什么樣的代碼示例會做這樣的事情呢?例如:def run_command(cmd):     # ??????print run_command('mysqladmin create test -uroot -pmysqladmin12')# Should output something like:# mysqladmin:      CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
查看完整描述

4 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

這要容易得多,但只適用于Unix(包括Cygwin)。

import commandsprint commands.getstatusoutput('wc -l file')

它返回一個元組,其中包含(RETURE_VALUE,輸出)

這只適用于python2.7*在python3..對于在這兩種情況下都有效的解決方案,請使用subprocess模塊相反:

import subprocess
output=subprocess.Popen(["date"],stdout=PIPE)response=output.communicate()print response


查看完整回答
反對 回復 2019-06-01
?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

就像這樣:

def runProcess(exe):    
    p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while(True):
        # returns None while subprocess is running
        retcode = p.poll() 
        line = p.stdout.readline()
        yield line        if retcode is not None:
            break

注意,我將stderr重定向到stdout,它可能不是您想要的,但我也需要錯誤消息。

本函數一條接一條的收益(通常,您必須等待子進程完成,才能獲得整個輸出)。

就您的情況而言,使用如下:

for line in runProcess('mysqladmin create test -uroot -pmysqladmin12'.split()):
    print line,


查看完整回答
反對 回復 2019-06-01
?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

def run_command(command):
    p = subprocess.Popen(command,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    return iter(p.stdout.readline, b'')

用法與公認的答案相同:

command = 'mysqladmin create test -uroot -pmysqladmin12'.split()for line in run_command(command):
    print(line)


查看完整回答
反對 回復 2019-06-01
  • 4 回答
  • 0 關注
  • 1474 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號