0

I have two python scripts with the following structure:

# Script1.py
from optparse import OptionParser
def main():
    parser = OptionParser()
    parser.add_option("-a", "--add-foobar", action="store_true", help="set foobar true",
        dest="foobar", default=False)
    options, args = parser.parse_args()
    print options.foobar

if __name__ == "__main__":
    main()

# Script2.py
from Script1 import main as script1Main
def main():
    script1Main()

Is there a way to pass command line arguments from script 2 to script 1? Script 1 in this example is immutable, therefore this must be done only thorough optparse.

Alexander
  • 841
  • 1
  • 9
  • 23
  • I'm confused...how are you calling the scripts and why are you doing it this way? Why do you say that Script 1 is "immutable?" – Adam Smith May 20 '15 at 21:49
  • Both of these scripts have the executable bit set. They would be run in the command line (For example, *./Script1.py -a* or *./Script2.py*). Script 1 is immutable as in I cannot change the code in script 1. As to the why, that's a very good question! :D – Alexander May 20 '15 at 21:52

2 Answers2

2

If you don't pass any arguments to parse_args, it just uses the value of sys.argv[1:], which is going to be whatever arguments were passed when you called Script2.py. The fact that Script2.py calls Script1.main doesn't change that.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

Firstly, maybe use argparse instead. You can process all arguments in script 2, then pass the argument handle to script 1.

# Script1.py
def main(args):
    print args

# Script2.py
import argparse
from Script1 import main as script1Main

def main():
    parser = argparse.ArgumentParser(
    parser.add_option("-a", "--add-foobar", action="store_true", help="set foobar true", default=False)
    args = parser.parse_args()
    script1Main(args)

if __name__ == "__main__":
    main()
Community
  • 1
  • 1
Rain Lee
  • 511
  • 2
  • 6
  • 11