我如何制作一个 Python3 带有 argparse 的文件来读取文件的内容?

How would I make a Python3 file with argparse that would read the contents of a file?

我现在是一个 Python 菜鸟,因为我只用了几天,我想知道你会如何编写一个使用 argparse 的 Python 脚本读取包含大量 URL 的文件的内容并将内容设置为变量?例如:

root@user:~# python myscript.py -f "URLs.txt"

和 python shell 然后将打印变量

URLs = The contents of the file
print(URLs)

导致:

root@user:~# python myscript.py -f "URLs.txt"
https://whosebug.com/
https://whosebug.com/
https://whosebug.com/
root@user:~#

如有任何帮助,我们将不胜感激!

首先我建议:

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)

在我的目录中有一个 ramdom 文件产生:

0029:~/mypy$ python stack47119114.py -f foo.txt
    1,    2,     
    3,    4,    5

我们也可以使用 argparse.FileType 打开文件,但 with open 语法更可取。对于更大的问题,我会将 parse_args 放在 if __name__... 块中,并在函数中定义操作。

但基本点是argparse应该主要使用解析器,而不是完整的动作代码。它的目的是找出您的用户想要什么。在实际问题中,对该输入采取行动是函数和 类 的工作,它们是单独定义的(甚至可能在导入的模块中)。