简体   繁体   中英

Pass argparse arguments to different python modules

I need to pass user input from the command line into a different python module that I wrote.

I wrote a web scraper module that gathers info from a company wiki, that is used by my main script. I'm importing the web scraper to the main script as a module.

The problem is that when the user executes the main function and indicates that they want to run the web scraper they are prompted for a password. Even if they enter a password on the command line.

In the main script I'm going:

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)

In the web_scraper module I'm going:

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()

The web scraper module is a separate file that it's being shared by several other modules that also use it.

I would like the user to type his password on the command line and then pass that to the web scraper in the other module. So that the user doesn't have to type his password twice (once on the command line and once in the program).

How can I achieve this?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM