问题描述
我正在尝试编写一个 Python (v3.6.9) 程序,该程序以交互方式接受输入,然后将输出打印到 stdout
。我还想将输入批量输入到一个文件中,然后将其通过管道传输到一个 python 程序中,并让该程序以相同的方式运行。批处理后,我还想继续与程序进行交互。我做了一些初步研究,发现 stdin 可以是 FIFO 或 tty。处理这个问题的方法是检查正在给出什么样的输入并采取相应的行动。我有以下程序:
#inputtest.py
import sys,os,stat
print("isatty():",sys.stdin.isatty())
print("isfifo():",stat.S_ISFIFO(os.fstat(0).st_mode))
def dosomething(inputline,num):
print(f"{num}: dosomething - inputline was: {inputline}")
command_number = 1
if stat.S_ISFIFO(os.fstat(0).st_mode) and not sys.stdin.isatty() :
for line in sys.stdin:
dosomething(inputline=line,num=command_number)
command_number = command_number + 1
sys.stdin = open("/dev/tty")
while True:
prompt = f"{command_number}: Type something > "
inputline = input(prompt)
dosomething(inputline=inputline,num=command_number)
command_number = command_number + 1
当我与它互动时,它看起来像这样:
(python3.6) jgodse@aurora:~/code/tmp/inputtest$ python inputtest.py
isatty(): True
isfifo(): False
1: Type something > Try something
1: dosomething - inputline was: Try something
2: Type something > 12345
2: dosomething - inputline was: 12345
3: Type something > Who kNows what to do
3: dosomething - inputline was: Who kNows what to do
4: Type something > ^CTraceback (most recent call last):
File "inputtest.py",line 21,in <module>
inputline = input(prompt)
KeyboardInterrupt
(python3.6) jgodse@aurora:~/code/tmp/inputtest$
(python3.6) jgodse@aurora:~/code/tmp/inputtest$ cat datafile
from datafile
this is a test
who kNows
(python3.6) jgodse@aurora:~/code/tmp/inputtest$ cat datafile | python inputtest.py
isatty(): False
isfifo(): True
1: dosomething - inputline was: from datafile
2: dosomething - inputline was: this is a test
3: dosomething - inputline was: who kNows
4: Type something >
由于我随后将 stdin 作为 /dev/tty 打开,它继续按预期进行交互(在“4: Type something >”提示之后),其中包括将参数输出到 input()
函数。>
此时我有一个问题。在管道版本中,作为 prompt
函数参数的 input()
永远不会被打印出来。为什么?有没有办法让它在管道版本中打印出提示?
这涉及到我的主要问题,我正在编写一个程序,该程序在 while
循环中具有更复杂的逻辑,其中一些逻辑包括通过 stdout
将文本打印到 print()
声明。当我尝试将文件通过管道传输到该程序时,该程序的交互式运行给出的任何输出都不会输出到屏幕上。
- 为什么会发生这种情况?
- 有没有办法捕获所有这些输出?
- 有没有办法调试这个问题,以便我找到问题的根源?
感谢我能得到的任何指导。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)