I found an answer on another Stack Overflow question about how to call a specific function def from within a Python file on the command line, however the function called doesn't take any arguments:
$ python -c 'from foo import hello; print hello()'
(I stripped the print statement as it seemed superfluous for my needs and am just calling the function in that case.)
Several answers say to use argument parsing, but that would require changes to several files that already exist and is undesirable.
The last answer on that question presents how to do what I want in Bash (I need to know how to do it in PowerShell).
$ ip='"hi"' ; fun_name='call_from_terminal'
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi
Here is my Python code:
def operator (string):
print("Operator here, I got your message: ", string)
And from PowerShell I want to call it doing something like:
$ python -c 'from myfile import operator; operator("my message here")'
The literal command I'm typing into PowerShell:
python -c 'from testscript import operator; operator("test")'
The literal error message I'm getting back:
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'test' is not defined
I think I understand the problem. PowerShell passes double-quotes to the executable even when you specify single quotes (it's trying to be helpful). Using showargs.exe (see http://windowsitpro.com/powershell/running-executables-powershell):
PS C:\> showargs python -c 'from testscript import operator; operator("test")'
python -c "from testscript import operator; operator("test")"
You should be able to escape the "
characters in your string to pass to the Python interpreter, either this way:
PS C:\> showargs python -c "from testscript import operator; operator(\""test\"")"
python -c "from testscript import operator; operator(\"test\")"
Or like this:
PS C:\> showargs python -c "from testscript import operator; operator(\`"test\`")"
python -c "from testscript import operator; operator(\"test\")"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With