[英]How do I get a Python program to take in parameters as inputs that come from standard input from the UNIX terminal?
For example - I want to do something like... 例如-我想做类似...
python DoublePendulum.py INPUT1 INPUT2
(where INPUT1
and INPUT2
are taken as variable inputs within the DoublePendulum program). (其中INPUT1
和INPUT2
作为DoublePendulum程序中的变量输入)。
$ python test.py arg1 arg2 arg3
In test.py 在test.py中
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
output 输出
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
Python also provided modules that helps you parse command-line options and arguments. Python还提供了有助于您解析命令行选项和参数的模块。 There are the following modules in the standard library: 标准库中包含以下模块:
$ python test.py one two five something
inside test.py 内部test.py
import sys
print(sys.argv[0:1], sys.argv[1:2], sys.argv[2:3], sys.argv[3:4], sys.argv[4:5])
will output as lists: 将输出为列表:
['test.py'] ['one'] ['two'] ['five'] ['something']
for my_var in sys.argv:
print(my_var)
will output: as strings 将输出:作为字符串
test.py one two five something
I made this function for that returns the parameter you want 我做了这个功能,返回您想要的参数
def give_me_arg(n):
num = len(sys.argv)
if n >= num:
print("Only enter:>",num,'<-and are this from 0 to ',num-1,':', sys.argv)
return ''
else:
for my_var in sys.argv[n:n+1]:
return my_var
my_var=give_me_arg(3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.