嘿伙计们,我遇到了从argpars调用函数的问题.这是我的脚本的简化版本,这是有效的,打印我给-s或-p的任何值
import argparse
def main():
parser = argparse.ArgumentParser(description="Do you wish to scan for live hosts or conduct a port scan?")
parser.add_argument("-s", dest='ip3octets', action='store', help='Enter the first three octets of the class C network to scan for live hosts')
parser.add_argument("-p", dest='ip', action='store',help='conduct a portscan of specified host')
args = parser.parse_args()
print args.ip3octets
print args.ip
然而,这对我来说在逻辑上相同会产生错误:
import argparse
def main():
parser = argparse.ArgumentParser(description="Do you wish to scan for live hosts or conduct a port scan?")
parser.add_argument("-s", dest='ip3octets', action='store', help='Enter the first three … 请考虑以下用法:
usage: do.py [-h] [-s | -m] filename
Run Code Online (Sandbox Code Playgroud)
这不是完整的用法.但我实际上想要的是filename成为文件的实际值而不是:
--filename FILENAME
Run Code Online (Sandbox Code Playgroud)
但是,也filename应该是可选的,所以我可以从标准输入中读取.想想catUNIX上的程序.
你只是说:
cat filename
Run Code Online (Sandbox Code Playgroud)
要么
cat
Run Code Online (Sandbox Code Playgroud)
编辑:现在,如果我执行程序do.py没有任何命令行选项,我会得到一个error: too few arguments.相反,即使我没有给它有效,我仍然希望它执行filename.我怎么做?
而不是用户必须使用script.py --file c:/stuff/file.txt有一种方法让用户可选地使用--file?所以相反,它看起来像script.py c:/stuff/file.txt但解析器仍然知道用户正在引用--file参数(因为它暗示).
我想从python stdin读取,但也在我的程序中有输入选项.当我尝试将选项传递给我的程序时,我得到错误文件未找到,我的参数被丢弃.
为了解析参数,我使用以下代码:
parser=argparse.ArgumentParser(description='Training and Testing Framework')
parser.add_argument('--text', dest='text',
help='The text model',required=True)
parser.add_argument('--features', dest='features',
help='The features model',required=True)
parser.add_argument('--test', dest='testingset',
help='The testing set.',required=True)
parser.add_argument('--vectorizer', dest='vectorizer',
help='The vectorizer.',required=True)
args = vars(parser.parse_args())
Run Code Online (Sandbox Code Playgroud)
为了从stdin读取,我使用以下代码:
for line in sys.stdin.readlines():
print(preprocess(line,1))
Run Code Online (Sandbox Code Playgroud)
命令行
echo "dsfdsF" |python ensemble.py -h
/usr/local/lib/python2.7/dist-packages/pandas/io/excel.py:626: UserWarning: Installed openpyxl is not supported at this time. Use >=1.6.1 and <2.0.0.
.format(openpyxl_compat.start_ver, openpyxl_compat.stop_ver))
Traceback (most recent call last):
File "ensemble.py", line 38, in <module>
from preprocess import preprocess
File "/home/nikos/experiments/mentions/datasets/preprocess.py", line 7, in <module>
with open(sys.argv[1], …Run Code Online (Sandbox Code Playgroud) 例如:
example.py
parser = argparse.ArgumentParser(description="Will take arguments... or none")
parser.add_argument("-a", action="store_true")
parser.add_argument("-b", action="store_true")
parser.add_argument("-c", action="store_true")
parser.add_argument("-d", action="store_true")
args = parser.parse_args()
print args
Run Code Online (Sandbox Code Playgroud)
我想将example.py设置a为True,但仅限于:
-a标志我试着乱搞
parser.set_defaults(a=True, b=False)
和
parser.add_argument("-a", action="store_true", default=True)
但他们将设置a到True即使我决定使用的b标志.
以下是解析参数的当前代码:
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--action', required=True, metavar='', nargs=1, help='{block|release|clear|show|show_extended|}')
parser.add_argument('-i', '--interface', required=True, metavar='', nargs=1, help='interface name')
parser.add_argument('-d', '--debug', action='store_true', help='debug prints')
parser.add_argument('--ips', metavar='ips', nargs='*', help='ip addresses to block')
parser.add_argument('--handles', metavar='handles', nargs='*', help='filters handles to delete (usually 800::xxx), run with [show] to see')
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
当我尝试执行它而不键入-a或-i时,我得到一个断言:
Traceback (most recent call last):
File "./block_traffic.py", line 112, in <module>
args = parser.parse_args()
File "/usr/lib/python2.7/argparse.py", line 1690, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "/usr/lib/python2.7/argparse.py", line 1722, in parse_known_args
namespace, args …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用argparse来创建一个我在Unix控制台中键入的实例:
python getFood.py --food <(echo Bread) --calories yes
Run Code Online (Sandbox Code Playgroud)
我已经实现了食物选项,并希望使用argparse添加卡路里是或否选项(二进制输入),这将决定是否从我导入的类调用卡路里方法.
我目前的代码主程序是:
parser = argparse.ArgumentParser(description='Get food details.')
parser.add_argument('--food', help='name of food to lookup', required=True, type=file)
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
这成功地允许我使用上面显示的第一个食物选项返回食物细节.
基本上我想添加第二个二进制选项,如果用户指示为true,将调用另一个方法.有关如何编辑我的主例程argparse参数的任何帮助?我对argparse还很新.
我使用docopt创建了一个cli规范,但是由于某种原因我必须将它重写为argparse
Usage:
update_store_products <store_name>...
update_store_products --all
Options:
-a --all Updates all stores configured in config
Run Code Online (Sandbox Code Playgroud)
怎么做?
什么是重要的我不想有这样的东西:
update_store_products [--all] <store_name>...
Run Code Online (Sandbox Code Playgroud)
我认为这将是这样的:
update_store_products (--all | <store_name>...)
Run Code Online (Sandbox Code Playgroud)
我尝试使用add_mutually_exclusive_group,但是我收到了错误:
ValueError: mutually exclusive arguments must be optional
Run Code Online (Sandbox Code Playgroud) 我注意到argparse在解析器中使用一种相当"神秘"的方式来创建变量.我知道变量的名称通常很容易推断:它是长或短选项的剥离版本(没有--或-分别).
此外,所有连字符(-)都变为下划线(_)成为合法的变量名称.
但这让我有一个关于冲突案件的问题(我知道这是一个极端的案例,但推断的部分对我来说有点神秘).例如程序:
import argparse
parser = argparse.ArgumentParser(description="A simple test about var names")
parser.add_argument("--max-value", type=int, help="the maximum value", metavar="Maximum-value")
parser.add_argument("-m", "--max_value", action="store_true", help="Whether to the use maximum value", dest="max1")
args = parser.parse_args()
print("max_value {}".format(args.max1))
print("max-value {}".format(args.max_value))
Run Code Online (Sandbox Code Playgroud)
显然使用两个非常相似的选项(--max-value和--max_value),它们导致相同的推断变量max_value.如果缺少任何一个选项,变量将max_value没有歧义.
但是当两者都存在时,显然--max_value得到了奖杯变量max_value而第二个(--max-value)获得了什么?我一直无法找到第二个变量.
那么,要访问它,我必须使用dest选项显式定义变量?如何获取可用变量名称列表?有趣的是,如果我使用dest=该--max_value选项,则--max-value获取预期变量,max_value同时--max_value得到非推断变量(在我的情况下max1)!
我也知道 …
是否可以在可选参数上添加一些子节?因此,用户更容易理解哪个参数与哪个参数相关?
我的意思是,例如psql --help,输出以下内容(我不知道psql解析库使用了哪些参数,但仅作为所需输出的一个好例子):
Usage:
psql [OPTION]... [DBNAME [USERNAME]]
General options:
-c, --command=COMMAND run only single command (SQL or internal) and exit
-d, --dbname=DBNAME database name to connect to (default: "oerp")
-f, --file=FILENAME execute commands from file, then exit
-l, --list list available databases, then exit
-v, --set=, --variable=NAME=VALUE
set psql variable NAME to VALUE
(e.g., -v ON_ERROR_STOP=1)
-V, --version output version information, then exit
-X, --no-psqlrc do not read startup file (~/.psqlrc)
-1 ("one"), --single-transaction
execute as a …Run Code Online (Sandbox Code Playgroud) argparse ×10
python ×10
python-3.x ×2
assertions ×1
docopt ×1
function ×1
python-2.7 ×1
stdin ×1
unix ×1