如何读取可变长度命令行参数

发布于 2025-02-12 11:49:27 字数 278 浏览 1 评论 0原文

我想给我的脚本输入命令行。 其输入参数为:

  1. 的脚本
  2. 我 第一个命令,其中我将通过命令行传递多个ID myScript.py ID ID1,ID2,ID3 ...

第二个命令,其中我将在末端a'-f'标志,该标志表示强制,必须执行该操作。

myScript.py ID 123,21,1,900 -F

我的问题是,我应该在脚本中阅读并使用这些参数? 谢谢 !

I want to give command line inputs to my script.
which has input arguments as :

  1. my script.py
  2. mode name (which is id)
  3. id numbers ( passed by ',' separations
    first command, in which I would pass multiple ids through command line
    myscript.py id id1,id2,id3...

second command, where I would a '-f' flag at the end which denotes force and it must do that operation.

myscript.py id 123,21,1,900 -f

My question is, how should I read in and use these arguments in the script?
Thank you !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薆情海 2025-02-19 11:49:27

您可以从sys库中获得参数。
基本实现

import sys

print(sys.argv)
if "-f" in sys.argv:
    print("force")
print(sys.argv[1], "=", sys.argv[2])
python file.py id id1,id2,id3 -f

> ['.\\file.py', 'id', 'id1,id2,id3', '-f']
> force
> id = id1,id2,id3

如果您需要作为字典格式,则可以查看 this

You can get argument from sys library.
Basic implementation

import sys

print(sys.argv)
if "-f" in sys.argv:
    print("force")
print(sys.argv[1], "=", sys.argv[2])
python file.py id id1,id2,id3 -f

> ['.\\file.py', 'id', 'id1,id2,id3', '-f']
> force
> id = id1,id2,id3

If you want as dictionary format you can view this

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文