user7988893
user7988893

Reputation:

pass a whole string as argument between python and bash

cat /tmp/testme
#!/usr/bin/env  python3
import sys
print(sys.argv[0])
print(sys.argv[1])

It is simple ,just to print argument passed from bash to python.

x="i am a book"
/tmp/testme "i am a book"
/tmp/testme
i am a book

The string i am a book can passed into python program as a whole string.

/tmp/testme  ${x}
/tmp/testme
i
echo ${x}
i am a book

Why python can't deal with ${x} i am a book as a whole,it get only the first character in the string as argument.

Upvotes: 0

Views: 1280

Answers (1)

Shane Bishop
Shane Bishop

Reputation: 4750

When you execute the line /tmp/testme ${x}, bash will expand the contents of x, and will ultimately execute /tmp/testme i am a book. Therefore, sys.argv will become ['/tmp/testme', 'i', 'am', 'a', 'book'].

To achieve the desired behaviour, ${x} should be quoted, like "${x}". Then bash will execute /tmp/testme 'i am a book'.

Here is an example with a bash script. With set -x, bash will print commands and their arguments as they are executed, after all variables have been evaluated.

$ cat testme
#!/usr/bin/env python3
import sys
print(sys.argv)

$ cat exampleBashScript.sh 
#!/usr/bin/env bash
set -x

x="i am a book"
./testme ${x}
./testme "${x}"

$ ./exampleBashScript.sh 
+ x='i am a book'
+ ./testme i am a book
['./testme', 'i', 'am', 'a', 'book']
+ ./testme 'i am a book'
['./testme', 'i am a book']

Upvotes: 1

Related Questions