如何将输入参数的值与文件进行比较,从而使文件中的行顺序得到“尊重”。例如:
文件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
,但是你可以简单地检查当-c
是migrate
时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/