2016-05-16 140 views
0

如何将输入参数值与文件进行比较,以便文件中的行顺序“受到尊重”。例如:将输入与文件进行比较并遵循序列

文件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开关强制切换?

在此先感谢。

+1

我强烈建议考虑['argparse'](https://docs.python.org/2/library/argparse.html)模块和在这种情况下[子命令(HTTPS: //docs.python.org/2/library/argparse.html#sub-commands)。 –

+0

谢谢Ilja的建议。我不知道这些,因为我对python相当陌生,并且还有2天的时间来完成这个工作并推动测试。猜猜我要在这两个燃烧午夜油:-) – Jaanna

回答

1

您需要检查序列的当前行是否使用-s标志指定。因此,您需要修改schemas值,以便它是一个包含所有模式的列表,然后您可以检查当前行是否等于其中一个模式。至于你的第二个问题,我不熟悉getopt,但你可以简单地检查当-cmigrate并且执行适当的错误处理时模式是否为空。

[...] 
schemas = [] 
[...] 
    elif opt in ("-s", "--schemas"): 
     schemas = arg.split(',') 
[...] 
if cmd == 'migrate': 
    if not schemas: # list is empty 
     # do error handling 
    for line in z: 
     if line in schemas: 
      print line 
+0

谢谢..是的,这工作。 – Jaanna

相关问题