我已经构建了一个应用程序,它可以在命令提示符中接收用户的文本输入。我想允许用户选择文本并使用该文本,而不是要求用户键入它
在linux/bash中,这是通过调用";xsel">(bash实用程序(,它输出当前选定的文本,然后通过管道将其发送到我的python脚本。在windows中,似乎没有一个简单的解决方案。。。知道如何在Windows中的python/batch/powershell/external实用程序中获取当前选择的命令行文本吗?
谢谢!
注意:我假设您只对当前控制台窗口中选择的文本感兴趣。
据我所知,在Windows上没有完美的解决方案[1],但您可以近似一个,但是,需要用户的合作,在做出选择后右键单击。
以下解决方案适用于常规控制台窗口(conhost.exe
(和windows终端:
-
在常规控制台窗口中;快速编辑"应该启用模式,以便使用鼠标直接选择文本。
-
要使解决方案发挥作用,用户必须将所选内容复制到剪贴板,如果没有提供直接输入,则稍后可以检索剪贴板的内容。这很容易通过在做出选择后右键点击(窗口内的任何位置(来实现,提示消息必须指示用户这样做。
这里有一个例子:
# Since the selection can only be obtained via the clipboard and we don't want preexisting
# clipboard content to interfere with the operation, we clear the clipboard first.
Set-Clipboard ''
# Define the prompt string to use with Read-Host containing instructions.
$prompt = @'
Enter a value and press Enter
- OR -
Select a string in this console window, RIGHT-CLICK and then press Enter
'@
# Prompt for user input until it is non-blank, either by direct input or via the selection.
do {
$userInput = Read-Host $prompt
if (-not $userInput) { # No direct input, try to get the selection from the clipboard.
$userInput = Get-Clipboard
}
} while (-not $userInput.Trim())
Write-Verbose -Verbose @"
You entered or selected:
«$userInput»
"@
[1]虽然(非PowerShell-friendly(技术原则上存在以查询Windows控制台的选择(涉及-"柔和地"弃用-GetConsoleSelectionInfo
WinAPI函数(,或者更一般地;监视";UI,如本答案所示(,这些技术不能由在控制台窗口中直接同步执行的代码使用,因为键入或提交命令总是涉及在将控制权返回到运行porgram的shell/a之前自动清除所选。在常规控制台窗口中,而不是在windows终端中,做出选择后的第一个Enter键实际上会将选择复制到剪贴板,然后清除选择并将控制权返回到shell/正在运行的程序,因此按Enter两次也可以,而不是右键单击然后按Enter
macOS上的终端也会首先清除选择
相比之下,在Linux上,至少X-Window-based terminals在这种情况下保留选择(通过Ubuntu 18.04附带的Gnome终端验证(,正如您的问题所示,可以与(可按需安装(xsel
实用程序组合以编程方式查询选择