如何用 /dev/tty 覆盖标准输入?
how to override stdin with /dev/tty?
我正在编写一个 git 预提交挂钩,但它需要用户输入并且挂钩不需要 运行 在交互式终端中。使用 Python 我可以做这样的事情来访问用户输入:
#!/usr/bin/python
import sys
# This is required because git hooks are run in non-interactive
# mode. You aren't technically supposed to have access to stdin.
# This hack works on MaxOS and Linux. Mileage may vary on Windows.
sys.stdin = open('/dev/tty')
result = input("Gimme some input: ")
在 Crystal 中执行此操作的适当方法是什么?
这似乎有效:
file = File.open("/dev/tty")
line = file.gets
p line
您不能重新分配 STDIN,我们也没有可重新分配的全局变量。我对此了解不多,也许可以使用 reopen 和 dup。但除此之外,我猜你可以在你的程序中使用 file
而不是 STDIN
。
你可以试试:
STDIN.reopen("/dev/tty")
通过结合@julian-portalier 的回答和@asterite 的回答,我们有了重新定义标准输入的方法:
STDIN.reopen(File.open("/dev/tty", "a+"))
我相信这只是 FileDescriptor#reopen
STDIN
、STDOUT
、STDERR
都可以这样重新打开。
我正在编写一个 git 预提交挂钩,但它需要用户输入并且挂钩不需要 运行 在交互式终端中。使用 Python 我可以做这样的事情来访问用户输入:
#!/usr/bin/python
import sys
# This is required because git hooks are run in non-interactive
# mode. You aren't technically supposed to have access to stdin.
# This hack works on MaxOS and Linux. Mileage may vary on Windows.
sys.stdin = open('/dev/tty')
result = input("Gimme some input: ")
在 Crystal 中执行此操作的适当方法是什么?
这似乎有效:
file = File.open("/dev/tty")
line = file.gets
p line
您不能重新分配 STDIN,我们也没有可重新分配的全局变量。我对此了解不多,也许可以使用 reopen 和 dup。但除此之外,我猜你可以在你的程序中使用 file
而不是 STDIN
。
你可以试试:
STDIN.reopen("/dev/tty")
通过结合@julian-portalier 的回答和@asterite 的回答,我们有了重新定义标准输入的方法:
STDIN.reopen(File.open("/dev/tty", "a+"))
我相信这只是 FileDescriptor#reopen
STDIN
、STDOUT
、STDERR
都可以这样重新打开。