这是我想如何调用脚本的示例:
python script.py -f file1.txt "string1" "string2" -f file2.txt "string3" "string4"
作为输入的每个文件都将有 2 个与该文件关联的字符串。可以有任意数量的文件。
为了简化,我试图得到这样的打印:
('file1.txt', 'string1', 'string2')
('file2.txt', 'string3', 'string4')
这是我到目前为止所拥有的:
import sys, os, traceback, optparse
import time
import re
#from pexpect import run, spawn
def main ():
global options, args
print options.filename
#for filename in options.filename:
# print filename
#f = file(filename,'r')
#for line in f:
# print line,
#f.close()
if __name__ == '__main__':
try:
start_time = time.time()
parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id$')
parser.add_option ('-f', '--file', dest='filename', help='write report to FILE', metavar='FILE', nargs=3)
parser.add_option ('-v', '--verbose', action='store_true', default=False, help='verbose output')
(options, args) = parser.parse_args()
#if len(args) < 1:
# parser.error ('missing argument')
if options.verbose: print time.asctime()
main()
if options.verbose: print time.asctime()
if options.verbose: print 'TOTAL TIME IN MINUTES:',
if options.verbose: print (time.time() - start_time) / 60.0
sys.exit(0)
except KeyboardInterrupt, e: # Ctrl-C
raise e
except SystemExit, e: # sys.exit()
raise e
except Exception, e:
print 'ERROR, UNEXPECTED EXCEPTION'
print str(e)
traceback.print_exc()
os._exit(1)
使用上面的脚本,我只得到第二个文件和相关字符串:
('file2.txt', 'string3', 'string4')