【发布时间】:2016-09-11 23:54:01
【问题描述】:
如何将输入参数的值与文件进行比较,以使文件中的行序列得到“尊重”。例如:
文件 sequence.txt 有以下条目
aaa
bbb
ccc
ddd
输入是这样的(带昏迷):
./run.py -c migrate -s ddd,bbb
然后输出是这样的:
bbb
ddd
这是我目前工作的脚本
#!/usr/bin/python
import sys
import getopt
import time
import os
def main(argv):
cmd = ''
schemas = ''
script_dir = os.path.dirname(__file__)
seq_file = "system/sequence.txt"
abs_file_path = os.path.join(script_dir, seq_file)
try:
opts, args = getopt.getopt(argv,"h:c:s",["cmd=","schemas="])
except getopt.GetoptError:
print './run.py -c=<command> -s=<schemas> '
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print './run.py -c=<command> -s=<schemas>'
sys.exit()
elif opt in ("-c", "--cmd"):
cmd = arg
elif opt in ("-s", "--schemas"):
schemas = arg
if cmd == "migrate" :
with open(abs_file_path) as z:
for line in z:
print line.rstrip('\n')
if __name__ == "__main__":
main(sys.argv[1:])
我知道我必须在位置print line.rstrip('\n') 进行比较,但我不知道该怎么做。有什么建议吗?
另外,如果 -c 具有“迁移”值,我怎样才能强制 -s 开关?
提前致谢。
【问题讨论】:
-
我强烈建议您查看
argparse模块,在本例中为sub-commands。 -
感谢 Ilja 的建议。我不知道这些,因为我对 python 还很陌生,还有 2 天的时间来做这件事并推动测试。猜猜我要在这两个上熬夜了:-)
标签: python linux command-line-arguments