英文:
What's the proper way to handle a KeyboardInterrupt during a subprocess that accepts "silent" input?
问题
使用Python 3.11.4时,当我使用subprocess.run
或subprocess.Popen
接受“静默输入”或“安全输入”,然后按下Ctrl+C,在之后使用常规的input
时不会显示所键入的文本。以下是一个可重现的示例:
import subprocess
try:
print("按下Ctrl+C键")
result = subprocess.run("echo $(read -s)", shell=True)
except KeyboardInterrupt:
pass
text = input("此处键入的文本不可见:")
print(text)
以下是我使用Popen尝试终止进程(但无济于事)的尝试:
import subprocess
result = subprocess.Popen("echo $(read -s)", shell=True)
try:
print("按下Ctrl+C键")
result.wait()
except KeyboardInterrupt:
result.kill()
pass
text = input("此处键入的文本不可见:")
print(text)
我该如何正确结束等待静默输入的进程,以便之后的常规输入会像正常一样显示出来?
编辑:我应该澄清一下,我正在构建一个使用subprocess
与特定命令行工具交互的界面。该工具以“静默”方式提示用户输入,但我能够使用echo $(read -s)
代替它来复现这个问题。
英文:
With Python 3.11.4, when I use subprocess.run
or subprocess.Popen
to accept "silent" input or "secure input" and then hit ctrl+c, using regular input
afterwards doesn't display text being typed. Here's a reproducible example:
import subprocess
try:
print("hit ctrl+c")
result = subprocess.run("echo $(read -s)", shell=True)
except KeyboardInterrupt:
pass
text = input("Text typed here is not visible: ")
print(text)
Here's my attempt, using Popen, to kill the process (but to no avail):
import subprocess
result = subprocess.Popen("echo $(read -s)", shell=True)
try:
print("hit ctrl+c")
result.wait()
except KeyboardInterrupt:
result.kill()
pass
text = input("Text typed here is not visible: ")
print(text)
How do I go about properly ending the process waiting for silent input so that regular input afterwards is displayed as it's typed?
Edit: I should clarify that I'm building an interface which uses subprocess
to interact with a specific command line tool. That tool prompts the user for input in a "silent" fashion, but I was able to reproduce the problem using echo $(read -s)
in its place.
答案1
得分: 1
从您的描述看,您可能正在寻找 getpass
函数?
from getpass import getpass
getpass("这里输入的文本不可见:")
英文:
It sounds like you might be looking for getpass
?
from getpass import getpass
getpass("Text typed here is not visible: ")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论