'How to pass a string variable from shell script to python with sys.argv?

I would like to pass a string variable from a Shell Script to my python script and have it stored in sys.argv[1]. Currently, this is my situation:

main.sh

TEST="This is a test"
python main.py $TEST

main.py

if __name__ == '__main__':
     print(sys.argv[1])

result:

This

How do I send $TEST so that sys.argv[1] = "This is a test"? I don't want to have to reconstruct the String after sending it.



Solution 1:[1]

Edit your main.sh to following :

TEST="This is a test"
python main.py "${TEST}"

Variable needs to expanded inside "" and will be transformed into its value.

main.py

if __name__ == '__main__':
     print(sys.argv[1])

Result:

This is a test

Solution 2:[2]

Just use:

python main.py "$TEST"

Solution 3:[3]

Just like this:

import sys
TEST="This is a test"


if __name__ == '__main__':
     print(TEST, sys.argv[0])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Freddy Mcloughlan
Solution 3 Rares