简体   繁体   English

Python-在命令行中使用参数运行函数

[英]Python - Run function with parameters in command line

Is it possible to run a python script with parameters in command line like this: 是否可以在命令行中运行带有参数的python脚本,如下所示:

./hello(var=True)

or is it mandatory to do like this: 还是必须这样做:

python -c "from hello import *;hello(var=True)"

The first way is shorter and simpler. 第一种方法是更短和更简单。

Most shells use parentheses for grouping or sub-shells. 大多数外壳将括号用于分组或子外壳。 So you can't call any commands like command(arg) from a normal shell ...but you can write a python script (./hello.py) that takes an argument. 因此,您无法从普通外壳调用任何命令,例如command(arg) ...,但是您可以编写带有参数的python脚本(./hello.py)。

import optparse
parser = optparse.OptionParser()
parser.add_option('-f', dest="f", action="store_true", default=False)
options, remainder = parser.parse_args()
print ("Flag={}".format(options.f)) 

And the call it with python hello.py -f 然后用python hello.py -f调用它

./hello(var=True) would be impossible from REPL shell. ./hello(var=True)REPL shell中是不可能的。 In some case it could be useful to have python function available in your current shell session. 在某些情况下,在当前的shell会话中提供python函数可能会很有用。 Here a workaround to make your python functions available in your shell environment. 这是一个使您的python函数在您的shell环境中可用的解决方法。

# python-tools.sh

#!/usr/bin/env bash
set -a # make all available export all variable)

function hello(){
    cd "/app/python/commands"
    python "test.py" $@
}

Content of the python script python脚本的内容

#! /usr/bin/env python
# /app/python/commands/test.py script

import sys


def test(*args):
    print(args)


if __name__ == '__main__':

    if sys.argv[1] in globals().keys():
        print(sys.argv[1])
        globals()[sys.argv[1]](sys.argv[2:])
    else:
        print("%s Not known function" % sys.argv[1])

Then source python-tools.sh 然后获取python-tools.sh

source python-tools.sh

After the hello function is available hello功能可用后

$ hello test arg2 arg2
test
(['arg2', 'arg2'],)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM