例如,我有一些python文件,比如hello.py
,add.py
,square.py
。
这些文件的定义如下
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')
最佳答案
下面是一个在python中使用argparse all的示例。
您可以使用以下命令运行它:python pyshell.py hello "well hi"
python pyshell.py add 20 3.4
python pyshell.py square 24
Pyshell.py:-
import argparse
# Create Parser and Subparser
parser = argparse.ArgumentParser(description="Example ArgumentParser")
subparser = parser.add_subparsers(help="commands")
# Make Subparsers
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,help='first number')
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):
print arg
def add(x,y):
print x + y
def square(a):
print a**2
if args.func == 'hello':
hello(args.arg)
elif args.func == 'add':
add(args.x,args.y)
elif args.func == 'square':
square(args.a)