python - 将输入与文件进行比较并注意顺序

标签 python linux command-line-arguments

如何将输入参数的值与文件进行比较,从而使文件中的行顺序得到“尊重”。例如:

文件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 开关?

提前致谢。

最佳答案

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

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

关于python - 将输入与文件进行比较并注意顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37249732/

相关文章:

python - SQLAlchemy Automap 反向引用错误

python - 检查两个 3D numpy 数组是否包含重叠的 2D 数组

database - 什么是不打算持久化,但可以存储超过 1MB 的键值内存存储系统?

c - 将 argv[] 传递给 CreateProcess() 的方法

python - key 错误 : 'HTTP_HOST' when running django tests

python - Django:在添加之前检查对象是否已经存在

c++ - 在 C++ 程序中查找 linux 中已安装的程序

linux - 使用 xargs 在一行中执行带有各种变量的命令

c - 命令行中的参数

php - argv 和 argc 未定义或为空