0
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"

4

3 回答 3

2

抓取strfromsys.argv并将其转换为int.

import sys
try:
  numberIterations = int(sys.argv[1])
except IndexError:
  print "Usage: %s numberIterattions" % sys.argv[0]
  raise SystemExit(1)
于 2013-04-18T16:06:03.793 回答
1
import sys

sys.argv包含来自命令行的参数

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

于 2013-04-18T16:03:14.920 回答
1
import sys
numberIterations = sys.argv[1] if (len(sys.argv > 0) else _default_value_

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

如果使用 python >= 2.7 使用argparse模块而不是 optparse 因为 optparse 自 python 2.7 以来已被弃用

于 2013-04-18T16:04:00.160 回答