首页 > 解决方案 > 如何使用 vanila python 在命令行上获取参数?

问题描述

假设我在终端上运行它时有一个名为 this.py 的文件

this.py

我怎样才能让所有的论点都通过?如:

this.py -foo

我不想使用 argparse,只是 vanila python

可以说 this.py 是这样的:

#user/python_projects/this.py/
arguments = """ now here I need to find a way of a list of the arguments passed"""
def main(arguments):
    if arguments[0] == 'foo':
        print('bar')
    else:
        print('I like foo ):')
main(arguments)

如果我使用

this.py -foo

那么预期的结果是:'bar'

标签: python

解决方案


如果您使用sys,您应该能够使其工作:

$ cat this.py 
import sys
arguments = sys.argv
def main(arguments):
    if arguments[1] == 'foo':
        print('bar')
    else:
        print('I like foo ):')
main(arguments)

$ python this.py foo
bar

请注意,argument[0]当我认为您真正想要时使用您的示例argument[1]


推荐阅读