【问题标题】:Passing arguments for functions while opening python file from terminal in Linux在 Linux 中从终端打开 python 文件时为函数传递参数
【发布时间】:2016-05-16 02:01:11
【问题描述】:

我正在尝试通过 Linux 终端打开我拥有的 python 脚本,格式如下所示:

$ python file_name.py a,b,c

在这里,a、b、c 是我在为程序编写的代码中使用的变量。目前我通过要求用户使用命令输入输入来获取输入 var_name = input("输入输入:")

但是,我想在打开文件本身时传递这三个变量的值,如上述格式中所述。 我是否必须利用课程来做到这一点?

我写的代码是:

print"Hello!"
circle = []
n = input("Enter the number of elements in the circle 'N' :")

for i in range(0,n):
    circle.append(i)

print "The circle being formed is : " + str(circle)

m = input("Enter the value of M : ")
k = input("Enter the value of K : ")

index = m-1

while (len(circle)>k) : 
    del circle[index]
    index = index + (m-1)
    n = n - 1
    index = (index)%n 

print str(circle)

【问题讨论】:

    标签: python class arguments command-line-arguments variable-declaration


    【解决方案1】:

    如果您使用的是 Python 2.7(很有可能),您可以尝试argparser

    import argparse
    
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')
    
    args = parser.parse_args()
    print args.accumulate(args.integers)
    

    然后运行:

    $ python prog.py 1 2 3 4
    4
    
    $ python prog.py 1 2 3 4 --sum
    10
    

    【讨论】:

    • 如果您想在 OP 问题中的数字之间使用逗号,您可以使用 ast.literal_eval 作为 type 参数;这会将其转换为整数元组。例如。 parser.add_argument('integers', type=ast.literal_eval)。如果没有其他参数,或者只是 ast.literal_eval(sys.arvg[1])
    猜你喜欢
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多