简体   繁体   English

在Linux中从终端打开python文件时传递函数参数

[英]Passing arguments for functions while opening python file from terminal in Linux

I'm trying to open a python script i have through the terminal in Linux, in the format as shown below: 我正在尝试通过Linux中的终端打开我拥有的python脚本,格式如下所示:

$ python file_name.py a,b,c $ python file_name.py a,b,c

Over here a,b,c are variables that i'm using in the code i've written for the program. 在这里,a,b,c是我在为程序编写的代码中使用的变量。 Currently I'm getting input by asking the user to enter input using the command var_name = input("Enter input for a: ") 目前,我正在通过要求用户使用命令var_name = input(“ Enter input for a:”)输入输入

However i want to pass the value for these three variables while opening the file itself as mentioned in the format above . 但是我想按上述格式打开文件本身时传递这三个变量的值。 Will i have to make use of classes to do this? 我需要利用类来做到这一点吗?

The code i wrote is : 我写的代码是:

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)

If you're on Python 2.7 (which is very likely) you can try the argparser 如果您使用的是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)

And to run: 并运行:

$ python prog.py 1 2 3 4
4

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM