支持 sys.stdin.readlines() 以及 python 中的命令行参数?
Supporting sys.stdin.readlines() as well as command line arguments in python?
我正在开发一个可以直接启动或通过标准输入启动的应用程序。
目前,如果我不向应用程序传输任何数据,则永远不会收到 EOF,它会挂起等待输入(例如 ctrl+d)。该代码如下所示:
while True:
line = sys.stdin.readline()
print("DEBUG: %s" % line)
if not line:
break
我也试过:
for line in sys.stdin:
print("DEBUG (stdin): %s" % line)
return
然而,在这两种情况下,如果程序直接启动,则不会收到 EOF,因此它会挂起等待。
我看到一些 unix 应用程序在需要 stdin 输入的情况下传递单个 -
命令行标志,但我想知道是否有比这更好的解决方法?我希望用户能够互换使用该应用程序而无需记住添加 -
标志。
你能做的最好的事情就是检查标准输入是否是 TTY,如果是,就不要阅读它:
$ cat test.py
import sys
for a in sys.argv[1:]:
print("Command line arg:", a)
if not sys.stdin.isatty():
for line in sys.stdin:
print("stdin:", line, end="")
$ python3 test.py a b c
Command line arg: a
Command line arg: b
Command line arg: c
$ { echo 1; echo 2; } | python3 test.py a b c
Command line arg: a
Command line arg: b
Command line arg: c
stdin: 1
stdin: 2
$ python3 test.py a b c < test.py
Command line arg: a
Command line arg: b
Command line arg: c
stdin: import os, sys
stdin:
stdin: for a in sys.argv[1:]:
stdin: print("Command line arg:", a)
stdin:
stdin: if not sys.stdin.isatty():
stdin: for line in sys.stdin:
stdin: print("stdin:", line, end="")
我正在开发一个可以直接启动或通过标准输入启动的应用程序。
目前,如果我不向应用程序传输任何数据,则永远不会收到 EOF,它会挂起等待输入(例如 ctrl+d)。该代码如下所示:
while True:
line = sys.stdin.readline()
print("DEBUG: %s" % line)
if not line:
break
我也试过:
for line in sys.stdin:
print("DEBUG (stdin): %s" % line)
return
然而,在这两种情况下,如果程序直接启动,则不会收到 EOF,因此它会挂起等待。
我看到一些 unix 应用程序在需要 stdin 输入的情况下传递单个 -
命令行标志,但我想知道是否有比这更好的解决方法?我希望用户能够互换使用该应用程序而无需记住添加 -
标志。
你能做的最好的事情就是检查标准输入是否是 TTY,如果是,就不要阅读它:
$ cat test.py
import sys
for a in sys.argv[1:]:
print("Command line arg:", a)
if not sys.stdin.isatty():
for line in sys.stdin:
print("stdin:", line, end="")
$ python3 test.py a b c
Command line arg: a
Command line arg: b
Command line arg: c
$ { echo 1; echo 2; } | python3 test.py a b c
Command line arg: a
Command line arg: b
Command line arg: c
stdin: 1
stdin: 2
$ python3 test.py a b c < test.py
Command line arg: a
Command line arg: b
Command line arg: c
stdin: import os, sys
stdin:
stdin: for a in sys.argv[1:]:
stdin: print("Command line arg:", a)
stdin:
stdin: if not sys.stdin.isatty():
stdin: for line in sys.stdin:
stdin: print("stdin:", line, end="")