我试图通过python脚本从一个命令传递信息,并使用命令行参数动态更改输出。
ping 127.0.0.1 | FindAndHighlight.py -f "icmp"
我能够获取stdin输入并搜索icmp,如果我硬编码但是我无法弄清楚如何将命令行参数传递给脚本并同时接收管道数据。
我的代码核心如下。谢谢你的帮助!
def main(argv):
global debug, searchfor
try:
opts, args = getopt.getopt(argv, "h f:d", ["help", "debug", "find"])
except getopt.GetoptError:
print
print
print hilite("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 'hi-red', True)
print hilite("~~~~~~~~~~~~~~~~~~~~~!!!### Bad Switch! ###!!!~~~~~~~~~~~~~~~~~~~~~", 'hi-red', True)
print hilite("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 'hi-red', True)
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-d", "--debug"):
debug = True
elif opt in ("--f", "--find"):
searchfor = arg
source = "".join(args)
if __name__ == "__main__":
main(sys.argv[1:])
print "Search String is: ", searchfor
# searchfor = "icmp" ## If I was to hard code the search string I would un-comment this line
try:
buff = ''
while True:
buff += sys.stdin.read(1)
if buff.endswith('\n'):
if searchfor and searchfor in buff:
buff = buff.replace(searchfor, hilite(searchfor, 'red', False))
print buff[:-1]
buff = ''
except KeyboardInterrupt:
sys.stdout.flush()
pass