python - 运行一个从 PowerShell 显式获取参数的 Python 函数(不单独传递参数)

标签 python function powershell command-line

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

$ python -c 'from foo import hello; print hello()'

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

有几个答案说要使用参数解析,但这需要更改几个已经存在但不受欢迎的文件。

关于该问题的最后一个答案介绍了如何在 Bash 中执行我想执行的操作(我需要知道如何在 PowerShell 中执行此操作)。

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

这是我的 Python 代码:

def operator (string):
    print("Operator here, I got your message: ", string)

在 PowerShell 中,我想调用它做类似的事情:

$ python -c 'from myfile import operator; operator("my message here")'

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

python -c 'from testscript import operator; operator("test")'

我返回的字面错误消息:

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

最佳答案

我想我理解了这个问题。即使您指定单引号,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")"

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

PS C:\> showargs python -c "from testscript import operator; operator(\""test\"")"
python -c "from testscript import operator; operator(\"test\")"

或者像这样:

PS C:\> showargs python -c "from testscript import operator; operator(\`"test\`")"
python -c "from testscript import operator; operator(\"test\")"

关于python - 运行一个从 PowerShell 显式获取参数的 Python 函数(不单独传递参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34774005/

相关文章:

c - 有没有办法在c中创建一个可变长度的数组?

powershell - 为什么枚举后比较运算符不起作用?

powershell - 使用 2 遍编码设置 FFmpeg 进程优先级

python - 使用 Python 的 BeautifulSoup 不断返回 null,即使元素存在

javascript - 单击按钮后清除超时

python - Numpy:从子矩阵广播

PHP 函数返回不起作用

Windows 8 托盘通知错误

python - 正则表达式从python中的字符串中提取子字符串

Python列表推导式的误解