Stdin未按预期工作[Python]
我现在正在用Python进行一些练习,包括一个简单的行计数器,可以从命令行或stdin获取输入:Stdin未按预期工作[Python],python,stdin,Python,Stdin,我现在正在用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:
#### 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\u count1.py file\u with_4\u lines.txt,效果很好,我会得到以下输出:
File given at command line
4
但是,如果我通过python line_count1.py输入它以便它确实需要stdin,我会得到以下输出:
Needs stdin
_
但我从来没有对我的stdin条目做过任何事情。我可以用_4_lines.txt输入file_,但它只需要这样做,然后等待我输入另一个stdin行,直到我必须在Task Manager中删除代码时才会中断
是什么导致了这一切?根据我的理解,只要我为stdin输入一些应该触发其余代码的内容。但事实并非如此。我遗漏了什么?这与您的代码无关,但与终端上的
stdin
读取行为有关。有关详细信息,请参阅以下帖子:
编辑:
正如@Chase所说,在窗口上终止stdin的键是
Ctrl+Z
,在linux上是Ctrl+D
,这与您的代码无关,但与终端上的stdin
读取行为有关。有关详细信息,请参阅以下帖子:
编辑:
正如@Chase所说,在Windows上终止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))
如果没有在命令行中给出文件名,那么听起来您希望接受来自
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))
在
stdin
案例中键入file\u with_4_lines.txt
时,是否希望它读取file\u with_4_lines.txt
的内容?因为这不是stdin
的工作方式…它应该将文件变量与stdin相等,然后在count_行(file)中使用stdin。当您在stdin
案例中键入file_with_4_行.txt
时,您是否希望它用_4_行.txt读取file_的内容?因为这不是stdin的工作方式……它应该将文件变量与stdin相等,然后在计数行(file)中使用stdin。这似乎无法解决问题,用4行输入file_.txt^D不会退出stdin,用4行输入file_.txt也不会退出,然后在下一行使用^D。对未来的读者来说:问题是我在Windows上,不是Linux。Windows以Ctrl+Z结束,而不是Ctrl+D。这似乎解决不了问题,用_4_lines.txt ^D输入文件_不会退出stdin,用_4_lines.txt输入文件_也不会退出stdin,然后在下一行输入^D。对未来的读者来说:问题是我使用的是Windows,而不是Linux。Windows以Ctrl+Z结束,而不是Ctrl+D结束。