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.
You can use the command line arguments by using the sys. argv[] array. The first index of the array consists of the python script file name. And from the second position, you'll have the command line arguments passed while running the python script.
In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys. argv ) will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.
Open the terminal by searching for it in the dashboard or pressing Ctrl + Alt + T . Navigate the terminal to the directory where the script is located using the cd command. Type python SCRIPTNAME.py in the terminal to execute the script.
To execute a python script in a bash script you need to call the same command that you would within a terminal. For instance
> python python_script.py var1 var2
To access these variables within python you will need
import sys print sys.argv[0] # prints python_script.py print sys.argv[1] # prints var1 print sys.argv[2] # prints var2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With