简体   繁体   English

在python中支持sys.stdin.readlines()以及命令行参数吗?

[英]Supporting sys.stdin.readlines() as well as command line arguments in python?

I'm working on an application that can be launched directly, or via stdin. 我正在开发可直接或通过stdin启动的应用程序。

Currently if I don't pipe any data to the application an EOF is never received and it hangs waiting for input (such as ctrl+d). 当前,如果我不通过管道将任何数据传输到应用程序,则永远不会收到EOF,并且EOF会挂起以等待输入(例如ctrl + d)。 That code looks like: 该代码如下所示:

while True:
    line = sys.stdin.readline()
    print("DEBUG: %s" % line) 
    if not line:
       break

I've also tried: 我也尝试过:

for line in sys.stdin:
    print("DEBUG (stdin): %s" % line)
    return

However in both cases an EOF isn't received if the program is launched directly so it hangs waiting for it. 但是,在这两种情况下,如果直接启动程序,它都将挂起等待,但不会收到EOF。

I've seen some unix applications pass a single - command line flag in cases where stdin input is expected but I'm wondering if there's a better workaround then this? 我已经看到了一些UNIX应用程序通过一个单一的-的情况下命令行标志,在标准输入输入预期,但我不知道是否有更好的解决方法,然后呢? I'd rather the user be able to use the application interchangeably without remembering to add a - flag. 我希望用户可以互换使用该应用程序,而无需记住添加-标志。

The best you can do is to check whether standard input is a TTY, and, if so, not read it: 最好的办法是检查标准输入是否为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="")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM