【问题标题】:comparing input with a file and minding the sequence将输入与文件进行比较并注意顺序
【发布时间】: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


【解决方案1】:

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

[...]
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多