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?

3
  • Have you tried to google it? Commented Dec 22, 2017 at 10:17
  • write code in file in run it from file using sys.argv to get parameters. Commented Dec 22, 2017 at 10:19
  • 1
    You haven't provided the command line that causes the error. Commented Dec 22, 2017 at 10:53

2 Answers 2

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

Comments

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')"

2 Comments

@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.
Consider if the value of fileName itself contains a single quote.

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.