[英]Call a Python function and pass windows parameters from cmd.exe
I have a Python function that I want to run from the context-menu.我有一个 Python function 我想从上下文菜单中运行。 I am using the Windows Registry to call the function when a file is right clicked, and I want the function to receive the file selected.
当右键单击文件时,我正在使用 Windows 注册表调用 function,并且我希望 function 接收选定的文件。
The context menu item looks something like the Random Commands
option .上下文菜单项类似于
Random Commands
选项。
The function I wish to run is foo1()
in the file test1
:我希望运行的 function 是文件
test1
中的foo1()
:
# in script test1.py
def foo1():
import sys
print(sys.argv)
I tried approaching the problem using the python -c
switch to directly call the function:我尝试使用 python
-c
开关直接调用 function 来解决问题:
python -c "import test1; test1.foo1()" %1
However, the value of sys.argv
after selecting the file and executing is ['-c']
, which doesn't include the file selected.但是
sys.argv
选择文件执行后的值为['-c']
,不包括选择的文件。
I also tried using an argument parser to dynamically import and run the function:我还尝试使用参数解析器动态导入和运行 function:
# in file registry_parser.py
import argparse
import os
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--func_name')
parser.add_argument('-f', '--file_name')
parser.add_argument('-p', '--file_path')
args = vars(parser.parse_args())
sys.path.insert(0, args['file_path'])
exec(f"import {args['file_name']}")
exec(f"{args['file_name']}.{args['func_name']}(sys.argv)")
And the function I would call from the registry is (paths simplified):我将从注册表中调用的 function 是(路径简化):
registry_parser.py --func_name foo1 --file_name test1 --file_path "[PATH TO registry_parser.py]" %1
However, I either get an error registry_parser.py: error: unrecognized arguments: %1
or the " %1
" is parsed quite literally and ends up as a value in sys.argv.但是,我得到一个错误
registry_parser.py: error: unrecognized arguments: %1
或“ %1
”被完全按字面意思解析并最终作为 sys.argv 中的一个值。
Any help is appreciated.任何帮助表示赞赏。
So on all the forums I asked I never received a correct answer, but I found this Reddit Post that has an example to a solution.所以在我问过的所有论坛上,我从来没有收到过正确的答案,但我发现这个Reddit 帖子有一个解决方案的例子。 Hope this helps someone else.
希望这对其他人有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.