I know that I can run a python script from my bash script using the following:
python python_script.py
But what about if I wanted to pass a variable / argument to my python script from my bash script. How can I do that?
Basically bash will work out a filename and then python will upload it, but I need to send the filename from bash to python when I call it.
Use
and in your Python script
Beside
sys.argv
, also take a look at the argparse module, which helps define options and arguments for scripts.Embedded option:
Wrap python code in a bash function.
Use environment variables, to pass data into to your embedded python script.
http://bhfsteve.blogspot.se/2014/07/embedding-python-in-bash-scripts.html
and take a look at the getopt module. It works quite good for me!
To execute a python script in a bash script you need to call the same command that you would within a terminal. For instance
To access these variables within python you will need
I have a bash script that calls a small python routine to display a message window. As I need to use killall to stop the python script I can't use the above method as it would then mean running killall python which could take out other python programmes so I use
pythonprog.py "$argument"
& # The & returns control straight to the bash script so must be outside the backticks. The preview of this message is showing it without "`" either side of the command for some reason.As long as the python script will run from the cli by name rather than python pythonprog.py this works within the script. If you need more than one argument just use a space between each one within the quotes.