第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

運(yùn)行shell命令并捕獲輸出

運(yùn)行shell命令并捕獲輸出

收到一只叮咚 2019-06-01 10:27:55
運(yùn)行shell命令并捕獲輸出我想編寫一個(gè)函數(shù),它將執(zhí)行shell命令并返回其輸出。如一串不管是錯(cuò)誤還是成功的信息。我只想得到與命令行相同的結(jié)果。什么樣的代碼示例會(huì)做這樣的事情呢?例如: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貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊

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

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

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

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

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


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

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊

就像這樣:

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,它可能不是您想要的,但我也需要錯(cuò)誤消息。

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

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

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


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

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊

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

用法與公認(rèn)的答案相同:

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


查看完整回答
反對 回復(fù) 2019-06-01
  • 4 回答
  • 0 關(guān)注
  • 1463 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)