运行一个Python函数,它显式地从PowerShell获取参数(不单独传递参数)

Tuf*_*wer 4 python powershell command-line function

我在另一个Stack Overflow问题上找到了关于如何在命令行上从Python文件中调用特定函数def 的答案,但是调用的函数不带任何参数:

$ python -c 'from foo import hello; print hello()'
Run Code Online (Sandbox Code Playgroud)

(我删除了print语句,因为它对我的需求似乎是多余的,在这种情况下我只是调用函数.)

有几个答案说使用参数解析,但这需要更改已经存在的几个文件,这是不可取的.

关于该问题的最后一个答案介绍了如何在Bash中做我想要的事情(我需要知道如何在PowerShell中完成它).

$ ip='"hi"' ; fun_name='call_from_terminal'
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi
Run Code Online (Sandbox Code Playgroud)

这是我的Python代码:

def operator (string):
    print("Operator here, I got your message: ", string)
Run Code Online (Sandbox Code Playgroud)

从PowerShell我想称之为:

$ python -c 'from myfile import operator; operator("my message here")'
Run Code Online (Sandbox Code Playgroud)

我在PowerShell中输入的文字命令:

python -c 'from testscript import operator; operator("test")'
Run Code Online (Sandbox Code Playgroud)

我正在回复的文字错误消息:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'test' is not defined
Run Code Online (Sandbox Code Playgroud)

Bil*_*art 6

我想我明白了这个问题.即使您指定单引号(它试图提供帮助),PowerShell也会将双引号传递给可执行文件.使用showargs.exe(请参阅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")"
Run Code Online (Sandbox Code Playgroud)

您应该能够以"这种方式转义字符串中的字符以传递给Python解释器:

PS C:\> showargs python -c "from testscript import operator; operator(\""test\"")"
python -c "from testscript import operator; operator(\"test\")"
Run Code Online (Sandbox Code Playgroud)

或者像这样:

PS C:\> showargs python -c "from testscript import operator; operator(\`"test\`")"
python -c "from testscript import operator; operator(\"test\")"
Run Code Online (Sandbox Code Playgroud)