5

I am trying below commands

 python -c 'import sample; sample.Functionname()'
 python -c 'import sample; sample.printFxn("helloWorld")'

Both of these work well but when I pass a variable as an argument, I get the following error.

 File "<string>", line 1 import sample; sample.printFxn($filename) SyntaxError: invalid syntax

What is the proper way to pass a variable as an argument to a python function from bash?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Sivakami Subbu
  • 344
  • 3
  • 11

2 Answers2

7

Don't interpolate string variables into the command; pass the value as an argument to the Python script.

python -c 'import sys, sample; sample.printFxn(sys.argv[1])' "$fileName"
chepner
  • 497,756
  • 71
  • 530
  • 681
0

Single quotes (') prevent the shell from parsing a string an evaluating variables. You can use double quotes instead so the shell will evaluate your variable:

python -c "import sample; sample.printFxn('$fileName')"
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    @SivakamiSubbu Be aware that including the input this way is technically a security vulnerability. If you know for a fact that none of your files names can have been crafted into malicious Python code, it's okay to run it manually. But if this is programmatic and going to be used with input from untrusted sources, I'd look at actually using the command line arguments system. – jpmc26 Dec 22 '17 at 11:34
  • Consider if the value of `fileName` itself contains a single quote. – chepner Dec 22 '17 at 14:27