繁体   English   中英

Stdin无法按预期工作[Python]

[英]Stdin Not Working As Intended [Python]

我现在正在使用Python进行一些练习,包括一个简单的行计数器,该行计数器可以从命令行或stdin接收输入:

#### line_count1.py ####

import sys

def count_lines(file):
    n = 0
    for line in file:
        n = n + 1
    return n

if len(sys.argv) == 1:
    print("Needs stdin")
    file = sys.stdin
else:
    print("File given at command line")
    file = open(sys.argv[1])

print (count_lines(file))

如果我在命令行输入一个文件,即python line_count1.py file_with_4_lines.txt ,它的效果很好,并且我得到了输出:

File given at command line
4

但是,如果我输入它以便它确实需要通过python line_count1.py的 stdin,则会得到以下输出:

Needs stdin
_

但是我的stdin条目实际上并没有做任何事情。 我可以输入file_with_4_lines.txt ,但是它只需要它并等待我输入另一条stdin行,直到在必须杀死Task Manager中的代码之前,它才不会中断。

什么会导致这种情况发生? 根据我的理解,一旦我为stdin输入了一些东西,就应该触发其余代码。 但事实并非如此。 我想念什么?

这与您的代码无关,但与终端上的stdin读取行为有关。 有关更多信息,请参见以下帖子: https : //unix.stackexchange.com/questions/16333/how-to-signal-the-end-of-stdin-input

编辑:正如@Chase所说,在窗口上终止stdin的键是Ctrl+Z ,在Linux上是Ctrl+D

听起来好像您想接受stdin的文件名(如果未在命令行中给出),而此时您正在尝试计算stdin本身。

如果目标是处理给定文件(名称来自stdin或命令行),则应将代码更改为:

if len(sys.argv) == 1:
    # Prompt for and read a single line from stdin to get the desired file name
    filename = input("Needs stdin")  # On Py2, use raw_input, not input
else:
    print("File given at command line")
    # Use argument as filename
    filename = sys.argv[1]

# Open the name provided at stdin or command line
# Use with statement so it's properly closed when you're done
with open(filename) as file:
    print(count_lines(file))

暂无
暂无

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

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