I'm running through some exercises in Python right now, including a simple line counter that can take input from the command line or 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))
If I enter a file at the command line, ie python line_count1.py file_with_4_lines.txt, it works great, and I get the output:
File given at command line
4
However, if I enter it so that it DOES need stdin via python line_count1.py, I get the following output:
Needs stdin
_
But never actually does anything with my stdin entry. I can enter file_with_4_lines.txt, but then it just takes it and waits for me to input another stdin line, never breaking out until I have to kill the code in Task Manager.
What would be causing this to happen? From my understanding, as soon as I enter something for stdin that should trigger the rest of the code to go through. But it's not. What am I missing?
file_with_4_lines.txtwhen you typefile_with_4_lines.txtin thestdincase? Cause that's not howstdinworks...