溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

實(shí)時(shí)獲取Python的print輸出流方法

發(fā)布時(shí)間:2020-08-23 01:58:27 來(lái)源:腳本之家 閱讀:414 作者:wangshuang1631 欄目:開發(fā)技術(shù)

我的應(yīng)用場(chǎng)景是:使用shell執(zhí)行python文件,并且通過(guò)調(diào)用的返回值獲取python的標(biāo)準(zhǔn)輸出流。

shell程序如下:

cmd='python '$1' '$2' '$3' '$5' '$4
RESULT=eval $cmd
echo $RESULT

之前我的寫的python程序如下:

# coding: utf-8
import time
import json

def execute(_database, _parameter):
  print 'sleep start'
  sleepTime = 30
  print 'sleep ' , sleepTime , 'second.'
  time.sleep(sleepTime)
  print 'sleep done'
  testDic={'doneCode':0,'doneMsg':'Done','logList':'success'}
  return json.dumps(testDic, ensure_ascii=False)

if __name__ == "__main__":
  p = 'param'
  db = 'databsae'
  result = execute(db, p)
  print result

之后遇到的問(wèn)題是shell不能實(shí)時(shí)的獲取python的print流,也就是說(shuō)不是獲取第一條print語(yǔ)句之后,休眠了30秒之后才獲取最后一條print語(yǔ)句。

所有的print流在shell中都是一次性獲取的,這種情況對(duì)于執(zhí)行時(shí)間比較短的程序腳本沒(méi)什么影響,但是當(dāng)python程序需要執(zhí)行很長(zhǎng)時(shí)間,而需要通過(guò)print流追蹤程序,就影響比較大。

通過(guò)查閱資料,可知:

當(dāng)我們?cè)?Python 中打印對(duì)象調(diào)用 print obj 時(shí)候,事實(shí)上是調(diào)用了 sys.stdout.write(obj+'\n')

print 將你需要的內(nèi)容打印到了控制臺(tái),然后追加了一個(gè)換行符

print 會(huì)調(diào)用 sys.stdout 的 write 方法

以下兩行在事實(shí)上等價(jià):

sys.stdout.write('hello'+'\n')
print 'hello'

調(diào)用sys.stdout.flush()強(qiáng)制其“緩沖,這意味著它會(huì)寫的一切在緩沖區(qū)到終端,即使通常會(huì)在這樣做之前等待。

改動(dòng)后程序如下:

# coding: utf-8
import time
import json
import sys
def execute(_database, _parameter):
  print 'time 1:',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
  print 'sleep start.'
  for i in range(1,10):
    print 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:',i
    print 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb:',i*i
    print 'ccccccccccccccccccccccccccccccccccccccccccccccccccccccc:',i+i
    sys.stdout.flush()
    time.sleep(10)
  print 'sleep end '
  print 'time 2:',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
  testDic={'doneCode':0,'doneMsg':'Done','logList':'success'}
  return json.dumps(testDic, ensure_ascii=False)

if __name__ == "__main__":
  p = 'param'
  db = 'database'
  result = execute(db, p)
  print result

以上這篇實(shí)時(shí)獲取Python的print輸出流方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI