tnt1
tnt1

Reputation: 11

execute python script with shell script - variables determined in sh

I have determined variables in the shell script and now I would like to implement these variables for the execution of python script (python script requires variables determined within the shell script).

--------------------------- shell_script.sh--------------------------

# variables a and b are required for execution of my_pythonscript.py

a=hvariable_1

b=variable_2

python my_pythonscript.py a b


many thanks for your help and suggestions in advance

Upvotes: 1

Views: 1076

Answers (2)

PonasM
PonasM

Reputation: 191

shell_script.sh

A='your variable'
B='another variable'
python my_pythonscript.py "$A" "$B"

my_pythonscript.py

import sys
a = sys.argv[1]
b = sys.argv[2]

Please note: sys.argv[0] is the script name, in your case my_pythonscript.py

Also if you intend to use python 3.6 use python3 my_pythonscript.py a b.

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can pass them to your script as argument variables:

Your shell script:

#!/bin/bash

VARIABLE1='Hello'
VARIABLE2='World'

python example.py $VARIABLE1 $VARIABLE2

Your Python script:

import sys

if len(sys.argv) == 3:
    print(sys.argv[1] + ' ' + sys.argv[2] + '!')

The python script prints when run through shell script:

Hello World!

Upvotes: 1

Related Questions