简体   繁体   中英

How to capture user input from Bash prompt with Python

I am running mysql_secure_installation which prompts the user for the root database password and asks the user to enter Yes or No to some other initial setup options. How would I capture the root password that the user enters?

I'm thinking something like :

capture = subprocess.Popen(['mysql_secure_installation'], stdout=subprocess.PIPE)
root_pwd = capture.communicate()

I'd like to also feed in default options to the other prompts. How can I do that?

To intercept user input for a subprocess transparently, you could use pty.spawn() :

import os
import pty

def read(fd):
    data = os.read(fd, 512)
    print('got input %r' % data)
    return data

pty.spawn('mysql_secure_installation', stdin_read=read)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM