[英]Python interactive after reading sys.stdin
I'm trying to write a small graph parser that reads from stdin
and writes the processed output to stdout
along the lines of: 我正在尝试编写一个从stdin
读取的小图解析器,并将处理后的输出写入stdout
,其行如下:
# parser.py
G = defaultdict(list)
for line in sys.stdin:
node, neighbor = line.split()
G[node].append(neighbor)
print(G)
I would like to invoke the script with python -i parser.py < data.txt
and interact with the objects I've created, but the interpreter always exits after the code runs even when I invoke Python with the -i
option. 我想用python -i parser.py < data.txt
调用脚本并与我创建的对象交互,但是在代码运行后解释器总是退出,即使我用-i
选项调用Python也是如此。 NB The same thing occurs with ipython
; NB同样的事情发生在ipython
; it even confirms for me that I "really want to exit." 它甚至向我证实我“真的想退出。”
A workaround is to write the code to use a specific file passed in as an argument, but I was wondering if there is a way to make Python not exit the interpreter in the example above. 解决方法是编写代码以使用作为参数传入的特定文件,但我想知道是否有一种方法可以使Python不在上面的示例中退出解释器。
The REPL (interactive console) exits when it exhausts standard input. REPL(交互式控制台)在耗尽标准输入时退出。 Ordinarily, standard input is the console, so it only exits when you type ^D or call quit()
manually. 通常,标准输入是控制台,因此只有在您键入^ D或手动调用quit()
时才会退出。 But if you redirect stdin from a file, stdin will be exhausted when you reach the end of the file. 但是如果从文件重定向stdin,当到达文件末尾时stdin将会耗尽。
You can use argparse
to accept a file on the command line, defaulting to sys.stdin
: 您可以使用argparse
在命令行上接受文件,默认为sys.stdin
:
parser = argparse.ArgumentParser()
parser.add_argument('input', type=argparse.FileType(), nargs='?', default=sys.stdin)
args = parser.parse_args()
G = defaultdict(list)
for line in args.input:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.