python - 将 argparse 参数传递给不同的 python 模块
问题描述
我需要将用户输入从命令行传递到我编写的不同 python 模块中。
我编写了一个网络爬虫模块,该模块从公司 wiki 收集信息,我的主脚本使用该模块。我将网络爬虫作为模块导入到主脚本中。
问题是当用户执行主函数并表示他们想要运行网络爬虫时,系统会提示他们输入密码。即使他们在命令行上输入密码。
在主脚本中我要去:
import argparse
import getpass
from web_scraper import web_scraper
def authenticate():
auth = get_login()
auth = str(auth).replace('(','').replace('\'','').replace(',',':').replace(')','').replace(' ','')
return auth
def arguments():
parser = argparse.ArgumentParser(description='This is a program that lists the servers in EC2')
parser.add_argument(
"-u",
"--user",
default = getpass.getuser(),
help = "Specify the username to log into Confluence")
parser.add_argument(
"-d",
"--password",
help = "Specify the user's password")
options = parser.parse_args()
return options
write_data_to_confluence(auth, html, pageid, title):
print("Stuff happens here.")
def main():
html = 'hi'
pageid = 12345678
title = 'My Title'
options = arguments()
if update_account_list.lower() == 'y':
web_scraper()
if options.password and options.user:
user = options.user
password = options.password
auth = (user, password)
write_data_to_confluence(auth, html, pageid, title)
else:
auth = authenticate()
write_data_to_confluence(auth, html, pageid, title)
在 web_scraper 模块中,我将:
def authenticate():
auth = get_login()
auth = str(auth).replace('(','').replace('\'','').replace(',',':').replace(')','').replace(' ','')
return auth
web_scraper():
print("I'm scaping the web!") # code for this function doesn't matter to the problem
def main():
web_scraper()
网络爬虫模块是一个单独的文件,它被其他几个也使用它的模块共享。
我希望用户在命令行上输入他的密码,然后将其传递给另一个模块中的网络爬虫。这样用户就不必输入他的密码两次(一次在命令行,一次在程序中)。
我怎样才能做到这一点?
解决方案
你拥有一切,你只需要传递options
函数调用......
auth = authenticate(options)
def authenticate(options):
推荐阅读
- flutter - VS 代码中的颤振开发工具未激活,并出现错误“激活 Dart DevTools 失败”。
- java - 我怎样才能再次要求输入而不是仅仅出现错误
- pandas - Pandas 相关函数不适用于浮点数据
- c++ - 我应该使用类方法还是通过引用传递对象?
- splunk - 使用 splunk 发现蛮力攻击
- python - 为什么 PyroPPL 中的 `Distribution` 类有 `log_prob()` 方法但没有 `prob()` 方法?
- linux - 与 GNU Make 链接时参数列表太长
- node.js - 转换 fastify-static 服务文件的响应
- java - 我们如何在 Java 中对二维数组的按行升序和按列降序进行排序?
- github - 列表中的 GitHub Markdown 链接无法正确显示