如何将输入参数值与文件进行比较,以便文件中的行顺序“受到尊重”。例如:将输入与文件进行比较并遵循序列
文件sequence.txt具有以下enteries
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'](https://docs.python.org/2/library/argparse.html)模块和在这种情况下[子命令(HTTPS: //docs.python.org/2/library/argparse.html#sub-commands)。 –
谢谢Ilja的建议。我不知道这些,因为我对python相当陌生,并且还有2天的时间来完成这个工作并推动测试。猜猜我要在这两个燃烧午夜油:-) – Jaanna