1
1
################################################################################
3
# Copyright (c) 2011 The MadGraph Development team and Contributors
3
# Copyright (c) 2011 The MadGraph5_aMC@NLO Development team and Contributors
5
# This file is a part of the MadGraph 5 project, an application which
5
# This file is a part of the MadGraph5_aMC@NLO project, an application which
6
6
# automatically generates Feynman diagrams and matrix elements for arbitrary
7
7
# high-energy processes in the Standard Model and beyond.
9
# It is subject to the MadGraph license which should accompany this
9
# It is subject to the MadGraph5_aMC@NLO license which should accompany this
12
# For more information, please visit: http://madgraph.phys.ucl.ac.be
12
# For more information, visit madgraph.phys.ucl.ac.be and amcatnlo.web.cern.ch
14
14
################################################################################
15
15
""" A file containing different extension of the cmd basic python library"""
39
39
import madgraph.various.misc as misc
40
40
from madgraph import MG5DIR
42
except Exception, error:
44
logger.info('extended_cmd:'+str(error))
45
import internal.misc as misc
42
except ImportError, error:
44
import internal.misc as misc
48
49
pjoin = os.path.join
237
238
self.completion_prefix = ''
238
239
self.completion_matches = compfunc(text, line, begidx, endidx)
239
#print self.completion_matches
241
self.completion_matches = [ (l[-1] in [' ','@','=',os.path.sep]
242
and l or (l+' ')) for l in self.completion_matches if l]
241
self.completion_matches = [ l if l[-1] in [' ','@','=',os.path.sep]
242
else ((l + ' ') if not l.endswith('\\$') else l[:-2])
243
for l in self.completion_matches if l]
245
246
return self.completion_matches[state]
246
247
except IndexError, error:
248
249
# logger.error('\n Completion ERROR:')
249
250
# logger.error( error)
373
374
"""Extension of the cmd object for only the help command"""
375
376
def help_quit(self):
376
logger.info("syntax: quit")
377
logger.info("-- terminates the application")
377
logger.info("-- terminates the application",'$MG:color:BLUE')
378
logger.info("syntax: quit",'$MG:color:BLACK')
379
380
help_EOF = help_quit
381
382
def help_history(self):
382
logger.info("syntax: history [FILEPATH|clean|.] ")
383
logger.info(" If FILEPATH is \'.\' and \'output\' is done,")
383
logger.info("-- interact with the command history.",'$MG:color:BLUE')
384
logger.info("syntax: history [FILEPATH|clean|.] ",'$MG:color:BLACK')
385
logger.info(" > If FILEPATH is \'.\' and \'output\' is done,")
384
386
logger.info(" Cards/proc_card_mg5.dat will be used.")
385
logger.info(" If FILEPATH is omitted, the history will be output to stdout.")
387
logger.info(" > If FILEPATH is omitted, the history will be output to stdout.")
386
388
logger.info(" \"clean\" will remove all entries from the history.")
388
390
def help_help(self):
389
logger.info("syntax: help")
390
logger.info("-- access to the in-line help" )
391
logger.info("-- access to the in-line help",'$MG:color:BLUE')
392
logger.info("syntax: help",'$MG:color:BLACK')
392
394
def help_save(self):
393
395
"""help text for save"""
394
logger.info("syntax: save [options] [FILEPATH]")
395
logger.info("-- save options configuration to filepath.")
396
logger.info("-- save options configuration to filepath.",'$MG:color:BLUE')
397
logger.info("syntax: save [options] [FILEPATH]",'$MG:color:BLACK')
397
399
def help_display(self):
398
400
"""help for display command"""
399
logger.info("syntax: display " + "|".join(self._display_opts))
400
logger.info("-- display a the status of various internal state variables")
401
logger.info("-- display a the status of various internal state variables",'$MG:color:BLUE')
402
logger.info("syntax: display " + "|".join(self._display_opts),'$MG:color:BLACK')
402
404
class CompleteCmd(object):
403
405
"""Extension of the cmd object for only the complete command"""
517
507
if line.endswith('\\'):
518
508
self.save_line = line[:-1]
519
509
return '' # do nothing
523
513
line = line.split('#')[0]
525
515
# Deal with line splitting
526
if ';' in line and not (line.startswith('!') or line.startswith('shell')):
527
for subline in line.split(';'):
517
lines = line.split(';')
518
for subline in lines:
519
if not (subline.startswith("history") or subline.startswith('help') \
520
or subline.startswith('#*')):
521
self.history.append(subline)
528
522
stop = self.onecmd(subline)
529
523
stop = self.postcmd(stop, subline)
532
526
# execute the line command
527
self.history.append(line)
535
530
def postcmd(self,stop, line):
569
564
# Ask a question with nice options handling
570
565
#===============================================================================
571
566
def ask(self, question, default, choices=[], path_msg=None,
572
timeout = True, fct_timeout=None, ask_class=None):
567
timeout = True, fct_timeout=None, ask_class=None, alias={},**opt):
573
568
""" ask a question with some pre-define possibility
605
602
obj = SmartQuestion
607
question_instance = obj(allow_arg=choices, default=default,
608
mother_interface=self)
609
question_instance.question = question
605
choices += alias.keys()
607
question_instance = obj(question, allow_arg=choices, default=default,
608
mother_interface=self, **opt)
611
610
answer = self.check_answer_in_input_file(question_instance, default, path_msg)
612
611
if answer is not None:
613
answer = alias[answer]
615
answer = question_instance.default(answer)
618
question = question_instance.question
615
619
value = Cmd.timed_input(question, default, timeout=timeout,
616
620
fct=question_instance, fct_timeout=fct_timeout)
627
if value == default and ask_class:
628
value = question_instance.default(default)
718
729
error_text += '%s : %s\n' % (error.__class__.__name__,
719
730
str(error).replace('\n','\n\t'))
720
error_text += self.error_debug % {'debug': self.debug_output}
731
error_text += self.error_debug % {'debug':self.debug_output}
721
732
logger_stderr.critical(error_text)
723
735
# Add options status to the debug file
726
738
except Exception, error:
727
739
debug_file.write('Fail to write options with error %s' % error)
742
for card in ['proc_card_mg5.dat','param_card.dat', 'run_card.dat']:
744
ff = open(pjoin(self.me_dir, 'Cards', card))
745
debug_file.write(ff.read())
730
750
#stop the execution if on a non interactive mode
731
751
if self.use_rawinput == False:
735
757
def nice_user_error(self, error, line):
737
759
return self.child.nice_user_error(error, line)
942
968
new_history.append(cur_line)
944
970
new_history.reverse()
945
self.history = new_history
948
def clean_history(self, to_keep=['set','add','load'],
949
remove_bef_last=None,
950
to_remove=['open','display','launch', 'check'],
951
allow_for_removal=None,
953
"""Remove command in arguments from history.
954
All command before the last occurrence of 'remove_bef_last'
955
(including it) will be removed (but if another options tells the opposite).
956
'to_keep' is a set of line to always keep.
957
'to_remove' is a set of line to always remove (don't care about remove_bef_
958
status but keep_switch acts.).
959
if 'allow_for_removal' is define only the command in that list can be
960
remove of the history for older command that remove_bef_lb1. all parameter
961
present in to_remove are always remove even if they are not part of this
963
keep_switch force to keep the statement remove_bef_??? which changes starts
968
if __debug__ and allow_for_removal:
970
assert arg not in allow_for_removal
976
while nline > -len(self.history):
977
switch = False # set in True when removal pass in True
979
#check if we need to pass in removal mode
980
if not removal and remove_bef_last:
981
if self.history[nline].startswith(remove_bef_last):
985
# if this is the switch and is protected pass to the next element
986
if switch and keep_switch:
990
# remove command in to_remove (whatever the status of removal)
991
if any([self.history[nline].startswith(arg) for arg in to_remove]):
992
self.history.pop(nline)
995
# Only if removal mode is active!
997
if allow_for_removal:
998
# Only a subset of command can be removed
999
if any([self.history[nline].startswith(arg)
1000
for arg in allow_for_removal]):
1001
self.history.pop(nline)
1003
elif not any([self.history[nline].startswith(arg) for arg in to_keep]):
1004
# All command have to be remove but protected
1005
self.history.pop(nline)
1008
# update the counter to pass to the next element
971
self.history[:] = new_history
1011
974
def import_command_file(self, filepath):
1012
975
# remove this call from history
1013
976
if self.history:
1014
977
self.history.pop()
1016
979
# Read the lines of the file and execute them
1017
commandline = open(filepath).readlines()
980
if isinstance(filepath, str):
981
commandline = open(filepath).readlines()
983
commandline = filepath
1018
984
oldinputfile = self.inputfile
1019
985
oldraw = self.use_rawinput
1020
986
self.inputfile = (l for l in commandline) # make a generator
1155
1121
if tag in cmds:
1156
1122
cmds[tag].append(cmdname)
1158
cmds[tag] = [cmdname]
1124
cmds[tag] = [cmdname]
1161
1126
self.stdout.write("%s\n"%str(self.doc_leader))
1162
1127
for tag in self.helporder:
1163
1130
header = "%s (type help <topic>):" % tag
1164
1131
self.print_topics(header, cmds[tag], 15,80)
1165
1132
for name, item in cmds.items():
1292
1260
if len(args) == 0:
1293
1261
args.append(base)
1294
self.write_configuration(args[0], base, basedir)
1262
self.write_configuration(args[0], base, basedir, self.options)
1296
1264
def write_configuration(self, filepath, basefile, basedir, to_keep):
1297
1265
"""Write the configuration file"""
1399
1365
BasicCmd.preloop(self)
1402
def __init__(self, allow_arg=[], default=None, mother_interface=None,
1368
def __init__(self, question, allow_arg=[], default=None,
1369
mother_interface=None, *arg, **opt):
1370
self.question = question
1404
1371
self.wrong_answer = 0 # forbids infinite loop
1405
1372
self.allow_arg = [str(a) for a in allow_arg]
1406
1373
self.history_header = ''
1426
1393
self.stdout.write(line)
1427
1394
self.stdout.flush()
1429
return Cmd.list_completion(text, self.allow_arg)
1397
out[' Options'] = Cmd.list_completion(text, self.allow_arg)
1398
out[' Recognized command'] = BasicCmd.completenames(self, text)
1400
return self.deal_multiple_categories(out)
1430
1401
except Exception, error:
1433
1405
def reask(self, reprint_opt=True):
1434
1406
pat = re.compile('\[(\d*)s to answer\]')
1435
1407
prev_timer = signal.alarm(0) # avoid timer if any
1472
1445
elif line and hasattr(self, 'do_%s' % line.split()[0]):
1473
1446
return self.reask()
1447
elif self.value == 'repeat':
1449
elif len(self.allow_arg)==0:
1475
1452
raise Exception
1453
except Exception,error:
1477
1454
if self.wrong_answer < 100:
1478
1455
self.wrong_answer += 1
1479
print """%s not valid argument. Valid argument are in (%s).""" \
1480
% (self.value,','.join(self.allow_arg))
1481
print 'please retry'
1456
logger.warning("""%s not valid argument. Valid argument are in (%s).""" \
1457
% (self.value,','.join(self.allow_arg)))
1458
logger.warning('please retry')
1484
1461
self.value = self.default_value
1510
1488
self.stdout.flush()
1513
out[' Options'] = SmartQuestion.completenames(self, text, line)
1491
out[' Options'] = Cmd.list_completion(text, self.allow_arg)
1514
1492
out[' Path from ./'] = Cmd.path_completion(text, only_dirs = False)
1515
1493
out[' Recognized command'] = BasicCmd.completenames(self, text)
1517
1495
return self.deal_multiple_categories(out)
1518
1496
except Exception, error:
1499
def precmd(self, *args):
1503
return SmartQuestion.precmd(self, *args)
1521
1505
def completedefault(self,text, line, begidx, endidx):
1522
1506
prev_timer = signal.alarm(0) # avoid timer if any