Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python import of script with argparse [closed]

A = a script that is structured to be called by command-line with options that are parsed internally by the python argparse library. B= another script that should call inside itself functions used in A.

I was believing that doing in B an import of A was what I needed but it returns me the usage options and then exits from python interpreter.

Is there a way to preserve A and import it in B passing to it the args? or should I rewrite a avoiding the parser use?

like image 439
user2239318 Avatar asked Jan 11 '23 22:01

user2239318


1 Answers

In your script A, check if you are the "main script" before parsing arguments and doing A job, otherwise this will be ran too when you only need to use A as a library.

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-k", dest = "foo",  action='store_true')
    args = parser.parse_args()
    # do things...
like image 91
MatthieuW Avatar answered Jan 28 '23 07:01

MatthieuW