[英]Pass argparse arguments to different python modules
我需要将用户输入从命令行传递到我编写的不同 python 模块中。
我编写了一个从公司 wiki 收集信息的网络爬虫模块,该模块由我的主脚本使用。 我正在将 Web 抓取工具作为模块导入到主脚本中。
问题是当用户执行 main 函数并表示他们想要运行网络爬虫时,他们会被提示输入密码。 即使他们在命令行上输入密码。
在主脚本中,我将:
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):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.