argparse

Python argparse dict arg

天涯浪子 提交于 2019-12-03 05:53:20
问题 I want to receive a dict(str -> str) argument from the command line. Does argparse.ArgumentParser provide it? Or any other library? For the command line: program.py --dict d --key key1 --value val1 --key key2 --value val2 I expect the following dictionary: d = {"key1": "val1", "key2": "val2"} 回答1: Here's another solution using a custom action , if you want to specify dict key pairs together comma-separated -- import argparse import sys parser = argparse.ArgumentParser(description='parse key

Specifying default filenames with argparse, but not opening them on --help?

北战南征 提交于 2019-12-03 05:47:42
Let's say I have a script that does some work on a file. It takes this file's name on the command line, but if it's not provided, it defaults to a known filename ( content.txt , say). With python's argparse , I use the following: parser = argparse.ArgumentParser(description='my illustrative example') parser.add_argument('--content', metavar='file', default='content.txt', type=argparse.FileType('r'), help='file to process (defaults to content.txt)') args = parser.parse_args() # do some work on args.content, which is a file-like object This works great. The only problem is that if I run python

File as command line argument for argparse - error message if argument is not valid

∥☆過路亽.° 提交于 2019-12-03 04:41:18
问题 I am currently using argparse like this: import argparse from argparse import ArgumentParser parser = ArgumentParser(description="ikjMatrix multiplication") parser.add_argument("-i", dest="filename", required=True, help="input file with two matrices", metavar="FILE") args = parser.parse_args() A, B = read(args.filename) C = ikjMatrixProduct(A, B) printMatrix(C) Now I would like to note, that the argument of -i should be a readable file. How can I do that? I've tried adding type=open , type

Argparse“ArgumentError: argument -h/--help: conflicting option string(s): -h, --help”

匿名 (未验证) 提交于 2019-12-03 02:56:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: Recently, I am learning argparse module, Argument error occurred below the code import argparse import sys class ExecuteShell(object): def create(self, args): """aaaaaaa""" print('aaaaaaa') return args def list(self, args): """ccccccc""" print('ccccccc') return args def delete(self, args): """ddddddd""" print('ddddddd') return args class TestShell(object): def get_base_parser(self): parser = argparse.ArgumentParser() parser.add_argument('-h', '--help', action='store_true', help=argparse.SUPPRESS) parser.add_argument('-c', action='store',

Using argparse with function that takes **kwargs argument

匿名 (未验证) 提交于 2019-12-03 02:33:02
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I'm using argparse to take input and pass it to a function that takes as arguments two variables and **kwargs . Here's my function: import requests import sys import argparse def location_by_coordinate(LAT, LNG, **kwargs): if not kwargs: coordinate_url = "https://api.instagram.com/v1/locations/search?lat=%s&lng=%s&access_token=%s" % (LAT, LNG, current_token) r = requests.get(coordinate_url).text else: coordinate_url = "https://api.instagram.com/v1/locations/search?lat=%s&lng=%s&access_token=%s" % (LAT, LNG, current_token) for key, value in

I want Python argparse to throw an exception rather than usage

匿名 (未验证) 提交于 2019-12-03 01:58:03
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I don't think this is possible, but I want to handle exceptions from argparse myself. For example: import argparse parser = argparse.ArgumentParser() parser.add_argument('--foo', help='foo help', required=True) try: args = parser.parse_args() except: do_something() When I run it: $ myapp.py usage: myapp --foo foo myapp: error: argument --foo is required But I want it to fall into the exception instead. 回答1: You can subclass ArgumentParser and override the error method to do something different when an error occurs: class ArgumentParserError

python, argparse: enable input parameter when another one has been specified

匿名 (未验证) 提交于 2019-12-03 01:49:02
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 由 翻译 强力驱动 问题: In my python script, I want to be able to use an optional input parameter only when another optional parameter has been specified. Example: $ python myScript . py -- parameter1 value1 $ python myScript . py -- parameter1 value1 -- parameter2 value2 But NOT: $ python myScript . py -- parameter2 value2 How do I do this with argparse? Thanks! 回答1: Use a custom action: import argparse foo_default = None class BarAction ( argparse . Action ): def __call__ ( self , parser , namespace , values , option_string = None ): didfoo = getattr (

Getting Youtube data using Python

匿名 (未验证) 提交于 2019-12-03 01:22:02
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I'm trying to learn how to analyze social media data available on the web and I'm starting with Youtube. from apiclient.errors import HttpError from outh2client.tools import argparser from apiclient.discovery import build import pandas as pd DEVELOPER_KEY = "AIzaSyB_F1mCrDydEbGUosnZES-NW-mg1CaOyjI" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" argparser.add_argument("--q", help="Search term", default="apple product") argparser.add_argument("--max-results", help="Max results", default=50) args = argparser.parse_args()

Python argparse mutual exclusive group

匿名 (未验证) 提交于 2019-12-03 01:05:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: What I need is: pro [-a xxx | [-b yyy -c zzz]] I tried this but does not work. Could someone help me out? group= parser.add_argument_group('Model 2') group_ex = group.add_mutually_exclusive_group() group_ex.add_argument("-a", type=str, action = "store", default = "", help="test") group_ex_2 = group_ex.add_argument_group("option 2") group_ex_2.add_argument("-b", type=str, action = "store", default = "", help="test") group_ex_2.add_argument("-c", type=str, action = "store", default = "", help="test") Thanks! 回答1: add_mutually_exclusive_group

argparse fails when called from unittest test

匿名 (未验证) 提交于 2019-12-03 01:03:01
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: In a file (say parser.py ) I have: import argparse def parse_cmdline(cmdline=None): parser = argparse.ArgumentParser() parser.add_argument('--first-param',help="Does foo.") parser.add_argument('--second-param',help="Does bar.") if cmdline is not None: args = parser.parse_args(cmdline) else: args = parser.parse_args() return vars(args) if __name__=='__main__': print parse_cmdline() Sure enough, when called from the command line it works and give me pretty much what I expect: $ ./parser.py --first-param 123 --second-param 456 {'first_param':