Skip to content Skip to sidebar Skip to footer

Importing A Python Script From Another Script And Running It With Arguments

I have a python script which has been packaged up as a command line script (dbtoyaml.py in Pyrseas since you ask). I am running another python script from which I want to call this

Solution 1:

When I'm writing a command line script I oftentimes will specifically design my script so this is possible. The key is to parse the args separate from the main function.

For example the main function might look like this:

defmain(**kwargs):
    # the body of the script goes here

Then elsewhere in the module I will configure the arg parser, parse the args and pass the result into the main script:

def run():
    parser = ... # configure parser here
    configs = parse_args(parser)
    main(**configs)

That way, if someone wants to call the script from within Python, they can do so (it also makes testing much easier):

import somescript
somescript.main(option='value', option2='value2')

Unfortunately, it appears that the authors of the script you are using did not do anything like that. As stated in another answer you can overwrite sys.argv, then import the script. While that may feel hacky, it should be less resource intensive than opening a new process and calling the command separately.

Solution 2:

this seems like not the best way to do it but you can probably set sys.argv

import sys
sys.argv += ['-m','-H MYHOSTNAME' .... other options]
from pyrseas import dbtoyaml
dbtoyaml.main()

but really I have no idea what dbtoyaml.py lookslike or is

Post a Comment for "Importing A Python Script From Another Script And Running It With Arguments"