簡體   English   中英

在pexpect中將輸出顯示到終端-Python

[英]displaying output to the terminal in pexpect - Python

我正在使用pexpect使安裝程序pexpect ,效果很好。 但是,我想用某種stdout替換pexpect.interact() ,這將允許我跟蹤安裝程序的進度條:

Please wait while Setup installs on your computer.

 Installing
 0% ______________ 50% ______________ 100%
 #########################################

----------------------------------------------------------------------------
Setup has finished installing on your computer.

View readme file [Y/n]: n

[Errno 5] Input/output error

源代碼如下:

## A bunch of informations being given to the installer above
## Do you want install? y
child.sendline('y')
## now I keep tracking of the installation bar progress ... 
child.interact()
## View readme file [Y/n]: n
child.sendline('n')

所以最后一部分是手動完成的,一旦安裝完成,我就無法使用child.interact()了。 我該怎么做?

我必須做一次相同的事情。 問題是默認情況下,事情在行緩沖模式下工作。 這是我的解決方法:

在創建child (我假設這是pexpect.spawn ),您可以將屬性child.logfile設置為某種東西-不必從字面上看是日志文件,它可以是任何文件句柄。 在您的情況下,可以將其設置為sys.stdout但以無緩沖模式打開此文件句柄。

工作示例:

#!/usr/bin/env python

import pexpect
import sys
import time
import os

def potato():
    for i in range(20):
        time.sleep(0.1)
        sys.stdout.write(str(i))
        sys.stdout.flush()
    sys.stdout.write('bye\n')



if __name__ == '__main__':
    if sys.argv[-1] == 'potato':
        potato()
    else:
        child = pexpect.spawn(__file__ + ' potato')
        child.logfile = os.fdopen(sys.stdout.fileno(), 'w', 0)
        child.expect('bye')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM