我有几个可选参数,其中一个需要存储多个值 - 即它的类型既不是字符串也不是整数。argparse 是否支持其他类型的可选参数?
例如,我想要这个命令:
>>> python example1 test_project --name try1 3
Run Code Online (Sandbox Code Playgroud)
相当于这样的代码:
args.name = {'try1', '3'}
Run Code Online (Sandbox Code Playgroud)
这可能吗?或者,action='store_true'如果他选择此选项,我是否会被迫使用然后提示用户提供更多信息?
我有一个可以使用UNIX'find'命令获得的文件列表,例如:
$ find . -name "*.txt"
foo/foo.txt
bar/bar.txt
Run Code Online (Sandbox Code Playgroud)
如何将此输出传递给像hello.py这样的Python脚本,以便我可以使用Python的argparse库解析它?
谢谢!
有没有办法使用文件类型检查文件名参数argparse?如果我可以创建正确类型的容器对象,似乎可以通过 type 或choices 关键字来完成。
我期待传入的文件类型(例如,file.txt),argparse如果文件类型不正确(例如),我想给出其自动消息.txt。例如,argparse 可能会输出
usage: PROG --foo filename etc... error: argument filename must be of type *.txt.
Run Code Online (Sandbox Code Playgroud)
也许我们可以尝试检测文件名字符串不以“.txt”结尾,而不是检测错误的文件类型,但这需要复杂的容器对象。
我正在使用 argparse,我想要类似的东西: test.py --file hello.csv
def parser():
parser.add_argument("--file", type=FileType('r'))
options = parser.parse_args()
return options
def csvParser(filename):
with open(filename, 'rb') as f:
csv.reader(f)
....
....
return par_file
csvParser(options.filename)
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:TypeError 强制转换为 Unicode:需要字符串或缓冲区,找到文件。
我怎么能解决这个问题?
Argparse 不承认我的位置论点。这是设置:
parser = argparse.ArgumentParser()
parser.add_argument("url")
parser.add_argument("-u", "--username")
parser.add_argument("-p", "--password")
parser.add_argument("-d", "--depth", default=sys.maxsize)
parser.add_argument("-t", "--threads", default=4)
Run Code Online (Sandbox Code Playgroud)
在底部,我有这个:
if __name__ == "__main__":
if len(sys.argv) > 1:
print sys.argv
args = parser.parse_args(sys.argv)
if args.username is not None and args.password is not None:
auth = [args.username, args.password]
else:
auth = None
spider(args.url,
basic_auth=auth,
threads=int(args.threads),
depth=int(args.depth))
else:
parser.print_help() # Handle 0 command-line arguments
Run Code Online (Sandbox Code Playgroud)
当我在命令行上调用我的脚本时staunch$ ./spiderer.py http://www.example.com/,我得到了这个:
usage: spiderer.py [-h] [-u USERNAME] [-p PASSWORD] [-d DEPTH] [-t THREADS]
url
spiderer.py: error: unrecognized arguments: …Run Code Online (Sandbox Code Playgroud) I have a function inside a module that creates an argparse:
def get_options(prog_version='1.0', prog_usage='', misc_opts=None):
options = [] if misc_opts is None else misc_opts
parser = ArgumentParser(usage=prog_usage) if prog_usage else ArgumentParser()
parser.add_argument('-v', '--version', action='version', version='%(prog)s {}'.format(prog_version))
parser.add_argument('-c', '--config', dest='config', required=True, help='the path to the configuration file')
for option in options:
if 'option' in option and 'destination' in option:
parser.add_argument(option['option'],
dest=option.get('destination', ''),
default=option.get('default', ''),
help=option.get('description', ''),
action=option.get('action', 'store'))
return parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
A sample myapp.py would be:
my_options = [
{
"option": …Run Code Online (Sandbox Code Playgroud) 我试图通过命令行参数传递参数来追加一个url.以下是我的尝试方式:
import argparse
parser = argparse.ArgumentParser(description='Arguments')
parser.add_argument('input', metavar='input', type=str)
parser.add_argument('output', metavar='text', type=str)
args = parser.parse_args()
url = 'https://example.com/?z=12&text='+args.output+'&loc{}'
print url
Run Code Online (Sandbox Code Playgroud)
当我执行
python url.py text.csv hello
Run Code Online (Sandbox Code Playgroud)
它将第二个传递的参数附加到url.我想知道如何使第二个参数可选,这样即使不提供第二个参数,我也希望通过连接到url来打印url.这是我期待的输出:
当两个论点都给出:
python url.py text.csv hello
Run Code Online (Sandbox Code Playgroud)
输出应该是
https://example.com/?z=12&text=hello&loc{}
Run Code Online (Sandbox Code Playgroud)
当给出单个参数时
python url.py text.csv
Run Code Online (Sandbox Code Playgroud)
输出应该是
https://example.com/?z=12&text=&loc{}
Run Code Online (Sandbox Code Playgroud) 以下代码采用可以在 Python 端检索的单个字符串值。如何用带有空格的句子字符串来做到这一点?
from sys import argv
script, firstargument = argv
print "The script is called:", script
print "Your first variable is:", firstargument
Run Code Online (Sandbox Code Playgroud)
要运行它,我会传递这样的参数:
$ python test.py firstargument
Run Code Online (Sandbox Code Playgroud)
哪个会输出
The script is called:test.py
Your first variable is:firstargument
Run Code Online (Sandbox Code Playgroud)
一个示例输入可能是“程序运行的你好世界”,我想将其作为命令行参数传递,以存储在“第一个”变量中。
我有一个小的python脚本,argparse用于让用户定义选项。它为不同的模式使用两个标志,并使用一个参数让用户定义文件。请参见下面的简化示例:
#!/usr/bin/python3
import argparse
from shutil import copyfile
def check_file(f):
# Mock function: checks if file exists, else "argparse.ArgumentTypeError("file not found")"
return f
def main():
aFile = "/tmp/afile.txt"
parser = argparse.ArgumentParser(description="An example",formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)
parser.add_argument("-a", "--ay", help="Method A, requires file.", action='store_true')
parser.add_argument("-b", "--be", help="Method B, no file required.", action='store_true')
args = parser.parse_args()
f = args.file
a = args.ay
b = args.be
if a:
copyfile(f, f+".a")
elif b:
print("Method B")
if …Run Code Online (Sandbox Code Playgroud) python arguments parameter-passing optional-parameters argparse
我是 argparse 的新手,所以这可能是基础。
我更喜欢将所有字符串常量定义一次 ( blah = 'foo'),然后在整个代码中使用它。当我到达时set_defaults,似乎我仅限于 kwarg 类型的参数。
也就是说,parser.set_defaults(NUM=ONE)不将 NUM 视为字符串。这是一个更完整的例子:
ONE = 'one'
TWO = 'two'
SIX = 'six'
NUMBER_OPTS = [ONE, TWO, SIX]
NUM = 'num'
parser = argparse.ArgumentParser()
pform = parser.add_mutually_exclusive_group()
for opt in NUMBER_OPTS:
pform.add_argument('--'+opt, dest=NUM, action='store_const', const=opt)
parser.set_defaults(NUM=ONE) # Can't find a syntax to make this DWIM
args = parser.parse_args()
print("%s is %s" % (NUM, vars(args)[NUM]))
Run Code Online (Sandbox Code Playgroud)
所以 whileadd_argument将字符串作为目的地,set_defaults而不是。
argparse ×10
python ×10
python-2.7 ×2
arguments ×1
csv ×1
file-type ×1
find ×1
optparse ×1
python-3.x ×1
shell ×1
unit-testing ×1
unix ×1