python - 如何通过终端或 shell 脚本从 python 文件调用特定函数并将参数传递给该函数?

标签 python linux shell

我在 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/

相关文章:

python - 在 OpenCV Python 中设置像素值

java - 向 WiFi 上所有可用的机器广播消息

shell - getopts 和参数包含两个 '*' 的问题

linux - 如何使用命令行工具备份和恢复(或创建快照)Linux 机器?

linux - 出现错误时从 bash 函数可靠退出

bash - 如何在不回显的情况下从 shell 脚本获取密码

python - 奇怪的 os.chmod 行为

python - 在 Django loaddata 中,它会抛出 json 格式的错误,但对于 yaml 格式却可以正常工作,为什么?

python - 当 CheckListCtrlMixin 中的项目被选中时,wxPython 会发出什么事件?

arrays - bash 脚本中 Cat 的替代方案?