[英]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.
我想要使用本机python的答案,希望很简单。
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. 我的问题是我在tkinter应用程序中使用子进程,但是其中一个命令要求您编写Y / N,以确保要继续执行该操作。
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写入终端的方法:您确定要继续吗? (y/N)
(是/否)
I've tried by running subprocess.run("y") but that doesn't seem to work. 我已经通过运行subprocess.run(“ y”)进行了尝试,但这似乎不起作用。
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. 我正在Debian Linux上对此进行测试,并调用subprocess.getoutput()来询问是否要继续执行该命令,以便可以检查错误。
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. 这是“主要”代码,一切正常,但这只是我需要输入Y才能继续进行。
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. 如果可能有多个提示,则必须使用子流程模块中较复杂的选项之一,读取并解析命令输出以了解何时需要回复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.