【发布时间】:2021-09-05 13:52:47
【问题描述】:
你好!这是我在 StackOverflow 上的第一个问题,如果我做错了什么,请指导我。
所以我有一个 python 脚本,我想制作一个 shell 脚本,以便在运行时将文本文件传送到 python。
问题是从文件管道到 python 的文本没有显示在屏幕上。
这是我尝试过的代码:
python3 index.py < input.txt
index.py
while True:
x = input("Input: ")
print("Input ->", x)
输入.txt:
Test1
Test2
Test3
在我尝试运行命令后,结果是:
Input: Input -> Test1
Input: Input -> Test2
Input: Input -> Test3
Input: Input ->
Input: Traceback (most recent call last):
File "index.py", line 2, in <module>
x = input("Input: ")
EOFError: EOF when reading a line
(忽略错误)
管道中的文本不显示。不仅如此,它甚至不显示新行。
很遗憾,这不是我想要的结果:(
这是我预期的结果:
Input: Test1
Input -> Test1
Input: Test2
Input -> Test2
Input: Test3
Input -> Test3
...
我已经尝试了以下命令:
cat input.txt | python3 index.py
结果如上。
这是我尝试的另一种方法:
cat input.txt | tee /dev/tty | python3 index.py
结果仍然不是我所期望的:
Test1
Test2
Test3
Input: Input -> Test1
Input: Input -> Test2
Input: Input -> Test3
我还通过启动一个分离的屏幕会话并通过-X stuff "Test1^M" 发送文本来查看屏幕命令,但问题是我不想制作一个类似于循环文本行并使用屏幕命令的 shell 脚本发送。 (我希望python尽可能快地读取标准输入)
纯shell脚本可以做到吗?
感谢您的进一步回答。
【问题讨论】:
-
我认为
Input: Test1中的Test1来自您在终端中输入的任何内容,如果是管道,input.txt 的输出将进入 index.py 的输入,而无需中间人提示,这就是它不打印的原因。 -
关于一般指导,请拨打tour并阅读How to Ask。对于有问题的代码,请始终提供minimal reproducible example。也就是说,请查看您应用于问题的标签的描述。特别是“shell”有点无意义,“linux”根本不适用。