1

I am trying to run one python script (Main_Script) which is supposed to get argparse flag and this script at the same time calls another script(Sub_Script) which is also supposed to get the flag to input. And when I call Main_Script I get an error which says that I can't use the flag because it is not defined in the script but it is actually defined. The error notification makes me use the flag from subscript instead.

MAIN_SCRIPT

parser = argparse.ArgumentParser(add_help=True)
parser.add_argument('-p', '--print_positive_results', action='store_true')
args = parser.parse_args()

PRINT_POSITIVE = args.print_positive_results
#I then use rhi global variable PRINT_POSITIVE 

SUB_SCRIPT

import argparse
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument('-d', '--debug', action='store_true')
args = parser.parse_args()

And when I call python MAIN_SCRIPT.py -p I get this

usage: test_grammar.py [-h] [-d]
test_grammar.py: error: unrecognized arguments: -p

DEBUG = False
if (args.debug ):
    DEBUG = True
glibdud
  • 7,550
  • 4
  • 27
  • 37
  • 1
    Is `test_grammar.py` "MAIN_SCRIPT" or "SUB_SCRIPT"? – glibdud Apr 24 '19 at 12:17
  • your call directive `python MAIN_SCRIPT.py -p` does not match the program's output: `test_grammar.py: error: ...` So you likely do not call the module holding your main script. – woodz Apr 24 '19 at 12:21
  • Every active parser sees the same `sys.argv`. Either write them so they can live with each other's arguments (`parse_known_args` can help), or set things up so only one parser runs. Putting the parsing in a `if __name__` block prevents parsing on `import`. – hpaulj Apr 24 '19 at 18:34
  • test_grammar is subscript – Nick Babakov May 23 '19 at 07:13

1 Answers1

0

Seems like the command line args from the main script are passed through to the sub script.

You could try to (and probably should) wrap the argparse stuff into:

if __name__ == '__main__':
    <argparse stuff>

With this the code is only called when the script is called from the command line. The real code could be outsourced into a function. This way you can use the script from command line with argparse and only import the function from the script if you call it from another script:

Main script:

import argparse
import subscript

if __name__ == '__main__':
    parser = argparse.ArgumentParser(add_help=True)
    parser.add_argument('-p', '--print_positive_results', action='store_true')
    args = parser.parse_args()

    ...
    subscript.your_function(<whatever your args are>)
    ...

Sub script:

import argparse


def your_function(<your args>):
    <your code>


if __name__ == '__main__':
    parser = argparse.ArgumentParser(add_help=True)
    parser.add_argument('-d', '--debug', action='store_true')
    args = parser.parse_args()

    your_function(<whatever your args are>)
    ...
tilman151
  • 563
  • 1
  • 10
  • 20