我在 python 文件中有三个函数。我想通过 shell 脚本或通过终端从 python 文件调用特定函数并将参数传递给该 python 函数。有什么办法可以做到吗?
我试过 python -c "exec(open(filename.py).read()); functionName()"
但我不知道如何传递参数。
如何运行,
python -c "import a, sys; a.functionName(sys.argv[1])""sampleString"
来自 shell 脚本?
#!/bin/bash
import os
def abracadabra_personal(project):
directory = "/srv/http/Personal/" + project
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print("Error! Couldn't create project folder : " + directory)
def sample():
print("Your argument was got.")
以上是我的python代码。下面是我的 shell 脚本。
#!/bin/bash
# creates a personal project
function abracadabra_personal() {
cd
# python -c "import abracadabra, sys; abracadabra.sample(sys.argv[1])" $1
python -c "print("hi")"
echo $1
cd /srv/http/Personal/
}
# creates an office project
function abracadabra_office() {
cd
python abracadabra.py $1
cd /srv/http/Office/
}
# creates a learning project
function abracadabra_learning() {
cd
python abracadabra.py $1
cd /srv/http/Learning/
}
# creates a freelance project
function abracadabra_freelance() {
cd
python abracadabra.py $1
cd /srv/http/Freelance/
}
最佳答案
命令行参数在 sys.argv
中可用.
$ cat a.py
def functionName(arg):
print('my argument is {}'.format(arg))
$ python -c 'import a, sys; a.functionName(sys.argv[1])' 'hello world'
my argument is hello world
或者,输入 entry point在 Python 脚本中。然后就可以直接调用这个Python模块了。
$ cat b.py
def functionName(arg):
print('my argument is {}'.format(arg))
if __name__ == '__main__':
import sys
functionName(sys.argv[1])
$ python -m b 'hello world'
my argument is hello world
如果您在 shell 脚本中有 shell 变量,请记住在变量扩展周围使用双引号。
argument='hello world'
…
python -m the_python_module "$argument"
关于python - 如何通过终端或 shell 脚本从 python 文件调用特定函数并将参数传递给该函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56412838/