无效语法 - python
我有一组参数,它们的目标都是 'search_and'、'search_not'、'search_start'、'search_then' 和 'filename'。
我用来捕捉错误的代码是:
if ( options.filename is None) and ( (options.search_and is None) or (options.search_not is None) or (options.search_start is None) or (options.search_then is None):
parser.error(usage)
sys.exit()
这看起来可能是个小错误,有人能告诉我发生了什么吗?
编辑#1:
我在最后加了一个')',确保它正确关闭,但它仍然显示语法无效。
if ( options.filename is None) and ( (options.search_and is None) or (options.search_not is None) or (options.search_start is None) or (options.search_then is None)):
编辑#2:
这是我目前的代码。
import optparse from OptionParser
usage = "useage: %prog [options]"
parser = OptionParser(usage)
parser.add_option("-a", "--all", type="string", dest="search_and", help="find ALL lines in the file for the word1 AND word2")
parser.add_option("-b", "--all", type="string", dest="search_not", help="search and find the lines that contain words1 not word2")
parser.add_option("-c", "--all", type="string", dest="search_start", help="search and find a line that starts with word1 or word2")
parser.add_option("-d", "--all", type="string", dest="search_then", help="search and find a line that has word1 followed by word2")
parser.add_option("-f", "--file", type="string", dest="filename", help="file name"
if ( options.filename is None) and ( (options.search_and is None) or (options.search_not is None) or (options.search_start is None) or (options.search_then is None)):
当我运行代码时:
python script.py -a hi bye
我在 if 语句那里得到了语法无效的错误。
5 个回答
0
在你最开始的代码中,"( options.filename is None)" 这部分,你需要把最后的 ")" 去掉,改成下面的代码:
(options.filename is None
这样就能解决你的语法错误了。
1
这段话的意思是,这个做法和你想要的效果是一样的,而且可能会让人看起来稍微更容易理解一些。
if options.filename is None and None in [options.search_and, options.search_not, options.search_start, options.search_then]:
parser.error(usage)
sys.exit()
4
在if语句之前的那一行
parser.add_option("-f", "--file", type="string", dest="filename", help="file name"
没有一个闭合的右括号)。
Python解释器通常会在下一行报出这样的语法错误。所以,如果你在某一行遇到语法错误,建议你检查一下前面那一行。