python - 获取列表中的所有元素,直到其结束或另一个参数 Python
问题描述
例如,我有一个命令需要很少的非位置参数
send_dm -u def750 -n 15 -msg 世界你好!
它需要整个列表和索引参数
('-u', 'def750', '-n', '1', '-msg', 'Hello', 'world!')
def750 1 "Hello
使用此代码:
allowed_args = ["-u", "-n", "-msg"]
index = args.index("-u") + 1
u = str(args[index])
index = args.index("-n") + 1
n = str(args[index])
index = args.index("-msg") + 1
msg = str(args[index])
我需要从一开始就采用 -msg 参数
- 新论点的开始
- 参数列表结束
所以如果我做这样的事情
send_dm -msg 世界你好!-u def750 -n 15
我仍然会得到: def750 1 Hello World!
现在我唯一得到的是 -msg 参数之后的第一个元素,我不知道该怎么做
解决方案
-
也许尝试在每个参数的开头寻找
allowed_args = ["-u", "-n", "-msg"]
argumentDict = {
"-u": "",
"-n": "",
"-msg": ""
}
currentArgument = ""
for argument in args:
if argument.startswith("-"):
if argument not in allowed_args:
return # wrong argument given
currentArgument = argument
else:
if argumentDict[currentArgument] != "": # add space when already something given
argumentDict[currentArgument] += " "
argumentDict[currentArgument] += argument
然后,您可以通过以下方式访问您的参数
argumentDict["-u"]
argumentDict["-n"]
argumentDict["-msg"]
的输出
print(argumentDict)
将会
{'-u': 'def750', '-n': '1', '-msg': 'Hello world!'}
推荐阅读
- java - 当我使用 quarkus-resteasy-reactive-jackson 时,quarkus-resteasy-mutiny 扩展不存在警告
- python - 如何在 Locust 的多个类中使用多个主机
- php - 付款后终止会话并返回回调页面
- python - 为什么我的 BMI 代码显示错误的类别?例如,当我得到 BMI = 21.7 但它会打印 OVERWEIGHT 语句
- google-cloud-platform - 如何将文件和/或文件夹持久化到谷歌计算引擎永久磁盘中以在 GKE 中使用?
- reactjs - 如何在组件中执行更改而不在反应应用程序中设置状态?
- javascript - 我想使用哈希字符打印一个正方形,javascript
- perl - FCGI死了吗?现在有什么替代方案?
- python - 我正在创建一个 Django 应用程序。我在 urls.py 文件中遇到了困难。我想使用路径函数而不是 url 函数
- python-3.x - AttributeError:模块“deathbycaptcha”没有属性“SocketClient”