Pass multiple args from bash into python
I have a short inline python script that I call from a bash script, and I want to have it handle a multi-word variable (which comes from $*
). I expected this to just work:
#!/bin/bash
arg="A B C"
python -c "print '"$arg"'"
but it doesn't:
File "<string>", line 1
print 'A
^
SyntaxError: EOL while scanning string literal
Why?
I would like to explain why your code doesn't work.
What you wanted to do is that:
arg="A B C"
python -c "print '""$arg""'"
Output:
A B C
The problem of your code is that python -c "print '"$arg"'"
is parsed as python -c "print '"ABC"'"
by the shell. See this:
arg="A B C"
python -c "print '"A B C"'"
#__________________^^^^^____
Output:
File "<string>", line 1
print 'A
SyntaxError: EOL while scanning string literal
Here you get a syntax error because the spaces prevent concatenation, so the following B
and C"'"
are interpreted as two different strings that are not part of the string passed as a command to python interpreter (which takes only the string following -c
as command).
For better understanding:
arg="ABC"
python -c "print '"$arg"'"
Output:
ABC
The BASH script is wrong.
#!/bin/bash
arg="A B C"
python -c "print '$arg'"
And output
$ sh test.sh
A B C
Note that to concatenate two string variables you don't need to put them outside the string constants
链接地址: http://www.djcxy.com/p/29140.html上一篇: 连接字符串文字
下一篇: 将bash中的多个参数传递给python