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

I have a python script that was packaged as a command line script (dbtoyaml.py in Pyrseas as you ask).

I am running another python script from which I want to call it a script. Is it possible to import a module and artificially fill in the required arguments from my second script so as not to modify any pier code at all?

from pyrseas import dbtoyaml -- My initial script, which also takes arguments dbtoyaml.main(['-m','-H MYHOSTNAME' .... other options])

Not working for me yet.

I get a weird error:

 usage: checkSchemaChanges.py [-h] [-H HOST] [-p PORT] [-U USERNAME] [-W] [-c CONFIG] [-r REPOSITORY] [-o OUTPUT] [--version] [-m] [-O] [-x] [-n SCHEMA] [-N SCHEMA] [-t TABLE] [-T TABLE] dbname checkSchemaChanges.py: error: unrecognized arguments: MYHOSTNAME mydatabaseuser 

What is a mixture of my new script (checkSchemaChanges.py and MYHOSTNAME and mydatabaseuser below) and the parameters from dbtoyaml, which are all correct.

Could there be a double parameter set that argparse confuses?

+6
source share
2 answers

this doesn't seem like the best way to do this, but you can probably install sys.argv

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

but I really have no idea what dbtoyaml.py looks like or

+3
source

When I write a command line script, I often design my script, so this is possible. The key is to parse the arguments separately from the main function.

For example, the main function might look like this:

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

Then, in another place in the module, I will configure the arg parser, parse the arguments and pass the result to the main script:

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

Thus, if someone wants to call a script from Python, they can do it (this also simplifies testing):

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

Unfortunately, it seems that the authors of the script you used did nothing of the sort. As pointed out in another answer, you can overwrite sys.argv and then import the script. Although this may seem like a hacker, it should be less resource intensive than opening a new process and invoking a command separately.

+10
source

Source: https://habr.com/ru/post/982290/


All Articles