[英]How would I make a Python3 file with argparse that would read the contents of a file?
I'm kind of a Python noob at the moment as I've only been using it for aa few days and I was wondering how would you write a Python script that uses argparse to read the contents of a file containing numerous URLs and set the contents as a variable? 我现在有点像Python noob,因为我只使用了几天,而我想知道如何编写一个使用argparse读取包含大量URL的文件内容的Python脚本并设置内容作为变量? For example: 例如:
root@user:~# python myscript.py -f "URLs.txt"
and the python shell would then print the variable 然后python shell将输出变量
URLs = The contents of the file
print(URLs)
resulting in: 导致:
root@user:~# python myscript.py -f "URLs.txt"
https://stackoverflow.com/
https://stackoverflow.com/
https://stackoverflow.com/
root@user:~#
Any help would be greatly appreciated! 任何帮助将不胜感激!
For a start I'd recommend: 首先,我建议:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--foo')
args = parser.parse_args()
with open(args.foo, 'r') as f:
lines = f.read()
print(lines)
which with a ramdom file in my directory produces: 在我的目录中带有随机文件的文件会产生:
0029:~/mypy$ python stack47119114.py -f foo.txt
1, 2,
3, 4, 5
We could use a argparse.FileType
to open the file as well, but the with open
syntax is preferable. 我们也可以使用argparse.FileType
打开文件,但是with open
语法更可取。 For a larger problem I'd put the parse_args
in a if __name__...
block, and define the action in a function. 对于更大的问题,我会将parse_args
放在if __name__...
块中,然后在函数中定义操作。
But the basic point is that argparse
should be used primarily has a parser, not the full action code. 但基本要点是,应该首先使用argparse
来具有解析器,而不是完整的动作代码。 Its purpose is to find out what your user wants. 其目的是找出您的用户想要什么。 In a real problem, acting on that input is the job of functions and classes that are defined separately (maybe even in an imported module). 在一个实际的问题中,作用于该输入的是分别定义的函数和类的工作(甚至在导入的模块中也是如此)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.