2

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.

2
  • What is the output of print(sys.argv)? Commented May 12, 2022 at 11:41
  • @FreddyMcloughlan that will return a list of all the argv and filename. Example: ['main.py', 'This', 'is', 'a', 'test'] Commented May 12, 2022 at 11:43

2 Answers 2

7

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

Comments

2

Just use:

python main.py "$TEST"

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.