Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 849
Hoxlegion Avatar asked Dec 29 '25 16:12

Hoxlegion


1 Answers

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
like image 190
Januka samaranyake Avatar answered Jan 01 '26 04:01

Januka samaranyake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!