Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Python script from bash with argument

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.

like image 892
Jimmy Avatar asked Jan 04 '13 10:01

Jimmy


People also ask

How do I run a Python file in terminal with arguments?

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.

How do you pass an argument to a 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.

How do I run a Python script from bash terminal?

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.


1 Answers

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 
like image 77
iamthedrake Avatar answered Oct 17 '22 13:10

iamthedrake