异步执行的命令捕获 REPL 输入

Asynchronously executed command captures REPL input

我是 运行 Julia REPL 中的这样一个外部命令:

stream, process = open(`sudo cat file.txt`, "w", STDOUT)

命令 sudo cat file.txt 在 shell 中标准执行时要求输入密码,然后打印文件。

所以我将其粘贴到 REPL 中,按回车键并立即 returns,因为该进程是异步运行的。到目前为止一切正常。

但是当我开始在 REPL 中输入其他内容时,我输入的字符不会出现在屏幕上(sudo 要求输入密码),因为异步过程(大概)"stealing" 我正在输入的文字。

您对 open 工作原理的理解是正确的。正如您在评论中澄清的那样,您的问题是关于为什么 sudo 在终端中询问密码而不是从 stream 中读取。 Bob at https://serverfault.com/a/731943 很好地解释了这一点。引用答案的相关部分:

Actually, a typical invocation of sudo does not read the password from stdin at all. Instead, sudo will directly access the controlling terminal (a tty or pty, via the /dev/tty special file) and output the prompt and read characters directly. This can be seen in the tgetpass.c file in the sudo source.

sudo 能够使用 -S 标志从标准输入读取。如果您想从脚本中自己编写密码,可以使用它:

Otherwise, if you specifically request sudo to read from stdin, e.g. with the -S flag -- and it will also write the prompt to stderr. This is the case where MadHatter's answer applies.