最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2019年01月07日 10:31:46   作者:wangshuang1631  
今天小編就為大家分享一篇實(shí)時獲取Python的print輸出流方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

我的應(yīng)用場景是:使用shell執(zhí)行python文件,并且通過調(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

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

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

通過查閱資料,可知:

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

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

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

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

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

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

改動后程序如下:

# 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í)時獲取Python的print輸出流方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

延津县| 濮阳县| 陇川县| 衡阳市| 墨竹工卡县| 始兴县| 汉阴县| 蓝田县| 应城市| 方城县| 大新县| 桂东县| 勃利县| 嵊州市| 莲花县| 上饶市| 巩留县| 增城市| 涿鹿县| 乐都县| 黄平县| 诸暨市| 达州市| 嵊泗县| 南丹县| 海盐县| 富蕴县| 双城市| 宜章县| 黑龙江省| 都匀市| 石家庄市| 永仁县| 顺昌县| 云浮市| 铁岭市| 金乡县| 麻江县| 观塘区| 邯郸市| 贵溪市|