在 Pycharm 中使用 sys.stdin 从文件中读取 [英] Reading from a file with sys.stdin in Pycharm
问题描述
我正在尝试测试一个简单的代码,该代码使用 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("\t")
print name
我有我想输入的文件在同一个目录:lib.txt
I have the file I want to input in the same directory: lib.txt
如何使用输入文件在 Pycharm 中调试我的代码?
How can I debug my code in Pycharm with the input file?
推荐答案
您需要创建自定义运行配置,然后将您的文件作为参数添加到脚本参数"框中.请参阅 Pycharm 的在线帮助以获取分步说明指南.
You need to create a custom run configuration and then add your file as an argument in the "Script Parameters" box. See Pycharm's online help for a step-by-step guide.
但是,即使您这样做(正如您发现的那样),您的问题也不会解决,因为您没有解析正确的命令行参数.
However, even if you do that (as you have discovered), your problem won't work since you aren't parsing the correct command line arguments.
您需要改为使用 argparse
:
You need to instead use argparse
:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="The filename to be processed")
args = parser.parse_args()
if args.filename:
with open(filename) as f:
for line in f:
name, _ = line.strip().split('\t')
print(name)
这篇关于在 Pycharm 中使用 sys.stdin 从文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!