处理接受“静默”输入的子进程期间的 KeyboardInterrupt 的适当方法是什么?

huangapple go评论75阅读模式
英文:

What's the proper way to handle a KeyboardInterrupt during a subprocess that accepts "silent" input?

问题

使用Python 3.11.4时,当我使用subprocess.runsubprocess.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: ")

huangapple
  • 本文由 发表于 2023年6月22日 00:12:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定