143

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.

Jimmy
  • 12,087
  • 28
  • 102
  • 192
  • when execute `python python_script.py` in your default shell in Debian you are using bash already... so just do in your bash script: `python python_script.py arg1 arg2 ...` – oz123 Jan 04 '13 at 10:52
  • @Jimmy Unprepared Question I think, its very easy Link:http://www.tutorialspoint.com/python/python_command_line_arguments.htm – Grijesh Chauhan Jan 04 '13 at 10:54

8 Answers8

203

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
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
iamthedrake
  • 2,239
  • 1
  • 16
  • 13
  • 1
    Thanks. However this way restricts the python file for only one use case. Is there a way to call methods of a python file with dynamic parameters within bash scripts? In this way, we will be able to use the same python file. I tried to do this with calls python file methods with $var within bash script. But it somehow failed. – burcak Jun 24 '19 at 21:06
  • 1
    @burcak If you want to execute the python file parallelly based on the dynamic parameters, First construct the complete path <>/<> param1 param2|<>/<> param3 param4 in the bash script, then pass the output as an argument to the below python script, import sys import subprocess arg_str = " ".join(sys.argv[1:]) cmds = arg_str.split('|') for cmd in cmds: print('call -- ' + cmd) subprocess.Popen(cmd, shell=True) print('call cmds finished') – Thiru Jun 28 '19 at 18:59
  • Integer arguments are treated as string and not convertible with this method. – Saket Suraj Apr 05 '22 at 11:37
26

Beside sys.argv, also take a look at the argparse module, which helps define options and arguments for scripts.

The argparse module makes it easy to write user-friendly command-line interfaces.

miku
  • 181,842
  • 47
  • 306
  • 310
25

Use

python python_script.py filename

and in your Python script

import sys
print sys.argv[1]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
16

Embedded option:

Wrap python code in a bash function.

#!/bin/bash

function current_datetime {
python - <<END
import datetime
print datetime.datetime.now()
END
}

# Call it
current_datetime

# Call it and capture the output
DT=$(current_datetime)
echo Current date and time: $DT

Use environment variables, to pass data into to your embedded python script.

#!/bin/bash

function line {
PYTHON_ARG="$1" python - <<END
import os
line_len = int(os.environ['PYTHON_ARG'])
print '-' * line_len
END
}

# Do it one way
line 80

# Do it another way
echo $(line 80)

http://bhfsteve.blogspot.se/2014/07/embedding-python-in-bash-scripts.html

user77115
  • 5,517
  • 6
  • 37
  • 40
  • Was BASHING my head in looking for something like this. I think I had something similar but it was broken and this solved my issue (calling Bash, then Python, then back to Bash). THANK YOU! – Patrick Ruff May 04 '22 at 20:45
  • Just a side note: you don't need to use environment variables, you can directly substitute bash arguments into the python code e.g. print("$1") – justin Oct 25 '22 at 20:29
1

use in the script:

echo $(python python_script.py arg1 arg2) > /dev/null

or

python python_script.py "string arg"  > /dev/null

The script will be executed without output.

burseaner
  • 885
  • 2
  • 17
  • 28
1

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.

-1

and take a look at the getopt module. It works quite good for me!

HappyHacking
  • 878
  • 1
  • 12
  • 28
  • [the getopt docs](https://docs.python.org/2/library/getopt.html) start: _**Note:** The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() function or who would like to write less code and get better help and error messages should consider using the argparse module instead._ – cate Jul 06 '17 at 14:29
-1

Print all args without the filename:

for i in range(1, len(sys.argv)):
print(sys.argv[i])
Riade
  • 1