首页 > 解决方案 > 将 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()

网络爬虫模块是一个单独的文件,它被其他几个也使用它的模块共享。

我希望用户在命令行上输入他的密码,然后将其传递给另一个模块中的网络爬虫。这样用户就不必输入他的密码两次(一次在命令行,一次在程序中)。

我怎样才能做到这一点?

标签: python

解决方案


你拥有一切,你只需要传递options函数调用......

        auth = authenticate(options)
def authenticate(options):

推荐阅读