importing a python script from another script and running it with arguments

前端 未结 2 928
闹比i
闹比i 2020-12-15 10:30

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 wa

相关标签:
2条回答
  • 2020-12-15 11:28

    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:

    def main(**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.

    0 讨论(0)
  • 2020-12-15 11:29

    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

    0 讨论(0)
提交回复
热议问题