我在another stack overflow question上找到了关于如何从命令行的python文件中调用特定函数def的答案,但是函数名为doesn' t拍摄任何参数:运行一个从powershell显式接收参数的python函数(不需要单独传递参数)
$ 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没有问题。 –
@Bill_Stewart所有的powershell在这里都在调用python解释器。我很抱歉,我做了一个糟糕的工作,说我不想把这个参数作为额外的参数(比如通常在CLI上的参数)传递给python文件,然后必须做一些额外的工作来获取参数并调用该函数。我想从命令行中调用,就像在Python中一样,参数直接传递给函数,而不是作为python的参数。我主要提到与变量相关的任何语法问题。 – Tuffwer
“参数直接传递给函数而不是作为python的参数” - 你能解释一下你的意思吗?你在python命令行中指定的任何东西都是“python的参数”。 –