例如,我有像hello.py、add.py、square.py这样的python文件。这些文件的定义如下
hello.py:-
def hello(a):
print a #a is some name
add.py:-
def add(a,b):
print a+b #where a,b are numbers which I have to pass as arguments in command
square.py:-
def square(a):
print a**2 #where 'a' is a number我希望从shell脚本(例如pyshell.sh)执行这些文件,并希望生成以下命令
pyshell --hello name - then it has to execute hello.py
pyshell --add 4 5 - then it has to execute add.py
pyshell --square 2 - then it has to execute square.py我正在尝试使用这个代码
#! /usr/bin/python
import argparse
# Create Parser and Subparser
parser = argparse.ArgumentParser(description="Example ArgumentParser")
subparser = parser.add_subparsers(help="commands")
# Make Subparsers
hai_parser = subparser.add_parser('--hai', help='hai func')
hai_parser.add_argument("arg",help="string to print")
hai_parser.set_defaults(func='hai')
args = parser.parse_args()
def hai(arg):
print arg
if args.func == '--hai':
hai(args.arg)但是我遇到了一个错误
usage: 1_e.py [-h] {--hai} ...
1_e.py: error: invalid choice: 'name' (choose from '--hai')发布于 2017-04-20 04:39:54
下面是一个在python中使用argparse的示例。
您可以通过以下方法运行它:
python pyshell.py hello "well hi"python pyshell.py add 20 3.4python pyshell.py square 24
比:-
导入arg# Create parser和Sub解析器=argparse.ArgumentParser(description=“示例ArgumentParser")子解析器=parser.add_subparsers(help=”命令“)# Make subparser hello_parser = subparser.add_parser('hello',help='hello func') hello_parser.add_argument("arg",help="string to print") hello_parser.set_defaults(func='hello') add_parser = subparser.add_parser('add',help=‘add func") add_parser.add_argument("x",type=float,add_parser.add_argument("y",type=float,help='second number') add_parser.set_defaults(func='add') square_parser = subparser.add_parser('square',help=‘square func’) square_parser.add_argument("a",type=float,help='number to square') square_parser.set_defaults(func='square') args = parser.parse_args() def hello( arg ):打印arg def add(x,( y):打印x+y def square(a):如果args.func == 'hello':hello(args.arg) elif args.func == 'add':添加(args.x,args.y) elif args.func == 'square':square(args.a)发布于 2017-04-20 04:18:47
您可以在python脚本(如#! /usr/bin/python )中使用shebang,这样就可以像shell脚本一样执行这些文件,例如,如果使用shebang,python file.py可以作为file.py执行。因此,根据您的问题,您可以在shell脚本中调用开关情况下的这些脚本,如
#! /bin/bash
case ${1:-''} in
"hello")
/path/to/hello $2
;;
"add")
/path/to/add $2 $3
;;
"square")
/path/to/square $2
;;
*)
echo "Invalid option supplied"
exit 1
;;
exit 0如果在python脚本中不使用shebang,最好在/path/to/script.py前面添加/path/to/script.py,最好在脚本中使用shebang,然后使用absolute path。还请确保相应的脚本具有执行权限。
https://stackoverflow.com/questions/43509934
复制相似问题