简体   繁体   中英

Python3 Tkinter - Write input (y) to console for subprocess

I've been looking around for an answer to my problem but have been unlucky. I would like for the answer to work with native python and hopefully be simple.

My problem is that I'm using subprocess in my tkinter application, but one of the commands require you to write Y/N to be sure you want to proceed with the action.

So I'm looking for a way to write y into the terminal when a message like this appears: Are you sure you want to continue? (y/N)

I've tried by running subprocess.run("y") but that doesn't seem to work.

I'm testing this on Debian Linux and to call the command that asks if I want to proceed, is subprocess.getoutput() so that I can check for errors.

CODE

class RemovePublicKeyDialog:
def __init__(self, parent):
    top = self.top = Toplevel(parent)

    Label(top, text="Who to remove?").pack()

    self.e = Entry(top)
    self.e.pack(padx=5)

    b = Button(top, text="REMOVE", command=self.ok)
    b.pack(pady=5)

def ok(self):
    #print("value is " + self.e.get())
    key = self.e.get()
    cmd = subprocess.getoutput("gpg --delete-keys " + key)
    print(cmd)
    if ("key \"" + key + "\" not found" in cmd):
        messagebox.showerror("Error", "No such public key.")
    elif ("Delete this key from keyring?" in cmd):
        #subprocess.run("echo 'y'")
        messagebox.showinfo("Success", "Public key \"" + key + "\" deleted from keyring.")
    else:
        messagebox.showerror("Error", "Unknown error, did you input a key?")

    self.top.destroy()

This is the "main" code, everything works but it's just that I need to input Y to get it to proceed.

Many command line utilities have a flag that automatically answers yes to any prompts - if you have access to the source code of your particular command, adding such a flag if it doesn't have one (or simply making a custom version that never prompts) may be the easiest solution. Some commands automatically do this if not run directly from a terminal - are you sure that this is even a problem?

If you know that there will be a single prompt, you could try:
subprocess.run("echo y | your-command", shell=True)

If there may be multiple prompts, you'd have to use one of the more complex options in the subprocess module, reading and parsing the command output to know when a reply is needed.

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