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"
答案 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)
答案 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