1

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

4
  • I mean, unless I'm missing something, you basically have it. Command should just be python my_pythonscript.py "$a" "$b". Commented Jul 15, 2018 at 17:59
  • its not working. lets say that my_pythonscript.py : print(a+b) Commented Jul 15, 2018 at 18:49
  • "It's not working" isn't particularly helpful feedback. What's the traceback? Are you setting the variables within python as shown in either of the two answers? Commented Jul 16, 2018 at 13:27
  • It works as you recommended. I realized that I had an empty variable. Thank you for your generous help and sorry for the confusion. Commented Jul 21, 2018 at 6:32

2 Answers 2

1

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!
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.