Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

python - Reading from a file with sys.stdin in Pycharm

I am trying to test a simple code that reads a file line-by-line with Pycharm.

for line in sys.stdin:
    name, _ = line.strip().split("")
    print name

I have the file I want to input in the same directory: lib.txt

How can I debug my code in Pycharm with the input file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can work around this issue if you use the fileinput module rather than trying to read stdin directly.

With fileinput, if the script receives a filename(s) in the arguments, it will read from the arguments in order. In your case, replace your code above with:

import fileinput
for line in fileinput.input():
    name, _ = line.strip().split("")
    print name

The great thing about fileinput is that it defaults to stdin if no arguments are supplied (or if the argument '-' is supplied).

Now you can create a run configuration and supply the filename of the file you want to use as stdin as the sole argument to your script.

Read more about fileinput here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...