I'm still new to python and I have multiple scripts that I have to pass arguments into to run. They were all setup to run in the command line like:
python script1 -c config/config_file1.json -m import
python script2 -c config/config_file1.json -cl config/config_file2.json
python script3 -c config/config_file3.json -d name
I now I have to create a script to run all the the scripts above and I don't know even where to begin. I've seen sugestions for subprocess or sys.argv, but I don't know what's the best aproach for this case. All I need is to be able to run the main script to run all the 3 other scripts and know the best way to handle all the args I need to pass to them. Any suggestions would be much appreciated.
If the arguments for the scripts are static, then:
import subprocess
# This is like running `python script1 -c config/config_file1.json -m import` and your other commands
subprocess.call(["python", "script1", "-c", "config/config_file1.json", "-m", "import"])
subprocess.call(["python", "script2", "-c", "config/config_file1.json", "-cl", "config/config_file2.json"])
subprocess.call(["python", "script3", "-c", "config/config_file3.json", "-d", "name"])
If you need to pass in different arguments every time, then you can get them from input()
or the argparse
library (Personally prefer argparse
in this case):
import argparse
import subprocess
def get_args():
parser = argparse.ArgumentParser()
# The add_argument method takes this pattern: ("--flag", "-abreviated-flag", dest="variable_to_store_input", help="Help message to display for partcular argument")
parser.add_argument("--name", "-n", dest="name", help="Name to enter: --name Bill, OR -n Bill")
parser.add_argument("--age", "-a", dest="age", help="Age to enter: --age 21, OR -a 21")
# Add as many arguments as you need following this format.
args = parser.parse_args() # Collect and parse the inputed arguments
# Make sure needed arguments are there
if not args.age:
parser.error("No age specified! Use --help for more info.")
if not args.name:
parser.error("No name specified! Use --help for more info")
return args # If this line is reached, all of the arguments are filled
arguments = get_args() # Gets the arguments
name = arguments.name
age = arguments.age
# This is just like running the command: `python script1 --name <some-name> --age <some-age>`
subprocess.call(["python", "script1", "--name", name, "--age", age])
# You can also store the command:
command = ["python", "script1", "--name", name, "--age", age]
subprocess.call(command)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments