我想使用shell中的python模块(确切地说,是来自gnuplot的间接模块)。我不想为每个调用编写额外的脚本或实现一些I/O逻辑。
假设作为一个最小的工作示例,我有一个python模块module_foo.py
#!/usr/bin/python
def bar():
print(1,2,3)
我的问题是:
为什么不能像这里这样将模块加载和命令执行结合起来使用python模块?
$ python -m module_foo -c 'bar()'
执行的时候什么都不会发生。但真正起作用的是,只使用这样的命令调用
$ python -c 'import module_foo; module_foo.bar()'
1 2 3
或者这个
$ python -c 'from module_foo import *; bar()'
1 2 3
在加载模块之前,即使是语法错误的命令也被“接受”--而不是执行--我想(对bar
的调用没有关闭):
$ python -m module_foo -c 'bar('
$
但是,可以使用python单元测试使用-m
模块选项(来自python文档):
python -m unittest test_module1 test_module2
python手册对这两个选项都是这样写的:
-c command
Specify the command to execute (see next section). This terminates the option
list (following options are passed as arguments to the command).
-m module-name
Searches sys.path for the named module and runs the corresponding .py file as
a script.
因此,我希望能够在这个-m ... -c ...
中使用路径选项,但不能按反向顺序使用-c ... -m ...
‘。我漏掉了什么明显的东西吗?
发布于 2019-09-08 11:13:59
如果您希望您的Python模块是可执行的,并调用函数bar()
,则应该将其添加到python文件的末尾:
if __name__ == "__main__": # this checks that the file is "executed", rather than "imported"
bar() # call the function you want to call
然后打电话:
python module_foo.py
如果您想要更多的控制,可以将参数传递给脚本并从sys.argv
访问它们。
有关传递给脚本的参数的更多灵活性,请参见argparse解析模块。
https://stackoverflow.com/questions/57841346
复制相似问题