如何创建while循环数的命令行参数?

时间:2013-04-18 16:00:26

标签: python python-2.7

import os

commands = ['uname -v', 'whoami']

a = 0  
numberIterations = 2    # How to make a command line argument of a while loop number?  
while a < numberIterations:  
    print "#--- Iteration: %s ---#" % a  
    i = 0  
    while i < len(commands):  
        print "$", commands[i]  
        os.system(commands[i])  
        i = i + 1  
    print ""  
    a = a + 1  

我想以这种格式运行脚本:
 ./script.py "numberIterations"

3 个答案:

答案 0 :(得分:2)

str抓取sys.argv并将其转换为int

import sys
try:
  numberIterations = int(sys.argv[1])
except IndexError:
  print "Usage: %s numberIterattions" % sys.argv[0]
  raise SystemExit(1)

答案 1 :(得分:1)

import sys

sys.argv包含命令行中的参数

http://www.tutorialspoint.com/python/python_command_line_arguments.htm

答案 2 :(得分:1)

import sys
numberIterations = sys.argv[1] if (len(sys.argv > 0) else _default_value_

对于更复杂的命令行交互(例如,为命名参数./script.py --numIterations=2提供支持),请查看optparse模块或this tutorial

如果使用python&gt; = 2.7使用argparse模块而不是optparse,因为自Python python 2.7以来不推荐使用optparse