簡體   English   中英

輸入密碼時,Python子進程模塊無法重定向標准輸出?

[英]Python subprocess module could not redirect stdout when inputting a password?

我想用互動終端的子進程和發送密碼,但我注意到,我不能得到任何stdout ,如果一些程序調用getpass(prompt)http://www.gnu.org/savannah-checkouts/gnu/libc/manual/ html_node / getpass.html

那意味着我不能與sudossh交互,那么如何解決這個問題呢? 謝謝。

這是示例:

process = subprocess.Popen(['sudo', 'apt', 'update'],
                       bufsize=0,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       stdin=subprocess.PIPE)
while True:
    # prefix '>>' in parent process
    # but we could see the stdout without prefix, that means read() never return
    # the subprocess just ignored the redirect of stdout
    print('>>', process.stdout.read())
    time.sleep(1)

您的問題尚不清楚,但是我會盡力回答

如果要發送密碼,可以使用communication()方法

有關communication()的更多信息,請參見python子進程中的多個輸入和輸出。

所以你的代碼會像這樣

from subprocess import Popen,PIPE
proc = Popen(['sudo', 'apt', 'update'],
                       bufsize=0,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       stdin=subprocess.PIPE)

testoutput=proc.communicate(input='your password')[0] # This will enter the password and wait for the process to exit
print ''.join(testoutput)

暫無
暫無

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

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