~madteam/mg5amcnlo/series2.0

« back to all changes in this revision

Viewing changes to madgraph/interface/extended_cmd.py

  • Committer: olivier Mattelaer
  • Date: 2016-05-12 11:00:18 UTC
  • mfrom: (262.1.150 2.3.4)
  • Revision ID: olivier.mattelaer@uclouvain.be-20160512110018-sevb79f0wm4g8mpp
pass to 2.4.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
194
194
         If a command has not been entered, then complete against command list.
195
195
         Otherwise try to call complete_<command> to get list of completions.
196
196
        """
197
 
 
 
197
        
198
198
        if state == 0:
199
199
            import readline
200
200
            origline = readline.get_line_buffer()
217
217
                else:
218
218
                    try:
219
219
                        compfunc = getattr(self, 'complete_' + cmd)
220
 
                    except AttributeError:
 
220
                    except AttributeError, error:
 
221
                        misc.sprint(error)
221
222
                        compfunc = self.completedefault
 
223
                    except Exception, error:
 
224
                        misc.sprint(error)
222
225
            else:
223
226
                compfunc = self.completenames
224
227
                
273
276
                tmp += data
274
277
                tmp = os.path.expanduser(os.path.expandvars(tmp))
275
278
                out.append(tmp)
 
279
                # Reinitialize tmp in case there is another differen argument
 
280
                # containing escape characters
 
281
                tmp = ''
276
282
            else:
277
283
                out.append(data)
278
284
        return out
497
503
                              # answer which are not required.
498
504
        if not hasattr(self, 'helporder'):
499
505
            self.helporder = ['Documented commands']
 
506
 
 
507
    def preloop(self):
 
508
        """Hook method executed once when the cmdloop() method is called."""
 
509
        if self.completekey:
 
510
            try:
 
511
                import readline
 
512
                self.old_completer = readline.get_completer()
 
513
                readline.set_completer(self.complete)
 
514
                readline.parse_and_bind(self.completekey+": complete")
 
515
            except ImportError:
 
516
                pass
 
517
        if readline and not 'libedit' in readline.__doc__:
 
518
            readline.set_completion_display_matches_hook(self.print_suggestions)
 
519
 
 
520
    
 
521
    def cmdloop(self, intro=None):
500
522
        
501
 
    
 
523
        self.preloop()
 
524
        if intro is not None:
 
525
            self.intro = intro
 
526
        if self.intro:
 
527
            print self.intro
 
528
        stop = None
 
529
        while not stop:
 
530
            if self.cmdqueue:
 
531
                line = self.cmdqueue[0]
 
532
                del self.cmdqueue[0]
 
533
            else:
 
534
                if self.use_rawinput:
 
535
                    try:
 
536
                        line = raw_input(self.prompt)
 
537
                    except EOFError:
 
538
                        line = 'EOF'
 
539
                else:
 
540
                    sys.stdout.write(self.prompt)
 
541
                    sys.stdout.flush()
 
542
                    line = sys.stdin.readline()
 
543
                    if not len(line):
 
544
                        line = 'EOF'
 
545
                    else:
 
546
                        line = line[:-1] # chop \n
 
547
            try:
 
548
                line = self.precmd(line)
 
549
                stop = self.onecmd(line)
 
550
            except BaseException, error:
 
551
                self.error_handling(error, line)
 
552
                if isinstance(error, KeyboardInterrupt):
 
553
                    stop = True
 
554
            finally:
 
555
                stop = self.postcmd(stop, line)
 
556
        self.postloop()
 
557
            
502
558
    def no_notification(self):
503
559
        """avoid to have html opening / notification"""
504
560
        self.allow_notification_center = False
517
573
        
518
574
        if not line:
519
575
            return line
520
 
        line = line.lstrip()
521
576
 
522
577
        # Check if we are continuing a line:
523
578
        if self.save_line:
524
579
            line = self.save_line + line 
525
580
            self.save_line = ''
526
 
        
 
581
            
 
582
        line = line.lstrip()        
527
583
        # Check if the line is complete
528
584
        if line.endswith('\\'):
529
 
            self.save_line = line[:-1]
 
585
            self.save_line = line[:-1] 
530
586
            return '' # do nothing   
531
587
                
532
588
        # Remove comment
540
596
                if not (subline.startswith("history") or subline.startswith('help') \
541
597
                        or subline.startswith('#*')): 
542
598
                    self.history.append(subline)           
543
 
                stop = self.onecmd(subline)
 
599
                stop = self.onecmd_orig(subline)
544
600
                stop = self.postcmd(stop, subline)
545
601
            return ''
546
602
            
591
647
    #===============================================================================    
592
648
    def ask(self, question, default, choices=[], path_msg=None, 
593
649
            timeout = True, fct_timeout=None, ask_class=None, alias={},
594
 
            first_cmd=None, **opt):
 
650
            first_cmd=None, text_format='4', **opt):
595
651
        """ ask a question with some pre-define possibility
596
652
            path info is
597
653
        """
606
662
                timeout = self.options['timeout']
607
663
            except Exception:
608
664
                pass
609
 
                    
 
665
 
610
666
        # add choice info to the question
611
667
        if choices + path_msg:
612
668
            question += ' ['
613
 
            question += "\033[%dm%s\033[0m, " % (4, default)    
 
669
            question += "\033[%sm%s\033[0m, " % (text_format, default)    
614
670
            for data in choices[:9] + path_msg:
615
671
                if default == data:
616
672
                    continue
621
677
                question += '... , ' 
622
678
            question = question[:-2]+']'
623
679
        else:
624
 
            question += "[\033[%dm%s\033[0m] " % (4, default)    
 
680
            question += "[\033[%sm%s\033[0m] " % (text_format, default)    
625
681
        if ask_class:
626
682
            obj = ask_class  
627
683
        elif path_msg:
636
692
                                                   mother_interface=self, **opt)
637
693
        
638
694
        if first_cmd:
639
 
            question_instance.onecmd(first_cmd)
640
 
        
 
695
            if isinstance(first_cmd, str):
 
696
                question_instance.onecmd(first_cmd)
 
697
            else:
 
698
                for line in first_cmd:
 
699
                    question_instance.onecmd(line)
641
700
        if not self.haspiping:
642
701
            if hasattr(obj, "haspiping"):
643
702
                obj.haspiping = self.haspiping
651
710
                answer = alias[answer]
652
711
            if ask_class:
653
712
                answer = question_instance.default(answer)
 
713
            if hasattr(question_instance, 'check_answer_consistency'):
 
714
                question_instance.check_answer_consistency()
654
715
            return answer
655
716
        
656
717
        question = question_instance.question
657
718
        value =   Cmd.timed_input(question, default, timeout=timeout,
658
719
                                 fct=question_instance, fct_timeout=fct_timeout)
659
 
 
660
 
 
661
720
        
662
721
        try:
663
722
            if value in alias:
709
768
                    self.store_line(line)
710
769
                    return None # print the question and use the pipe
711
770
                logger.info(question_instance.question)
712
 
                logger.warning('The answer to the previous question is not set in your input file')
713
 
                logger.warning('Use %s value' % default)
 
771
                logger.info('The answer to the previous question is not set in your input file', '$MG:color:BLACK')
 
772
                logger.info('Use %s value' % default, '$MG:color:BLACK')
714
773
                return str(default)
715
774
        
716
775
        line = line.replace('\n','').strip()
732
791
            line = os.path.expanduser(os.path.expandvars(line))
733
792
            if os.path.isfile(line):
734
793
                return line
 
794
        elif any(line.lower()==opt.lower() for opt in options): 
 
795
            possibility = [opt for opt in options if line.lower()==opt.lower()]
 
796
            if len (possibility)==1:
 
797
                return possibility[0]
 
798
            
735
799
        # No valid answer provides
736
800
        if self.haspiping:
737
801
            self.store_line(line)
880
944
        """
881
945
        if '~/' in line and os.environ.has_key('HOME'):
882
946
            line = line.replace('~/', '%s/' % os.environ['HOME'])
 
947
        if '#' in line:
 
948
            line = line.split('#')[0]
 
949
             
883
950
        line = os.path.expandvars(line)
884
951
        cmd, arg, line = self.parseline(line)
885
952
        if not line:
896
963
                return self.default(line)
897
964
            return func(arg, **opt)
898
965
 
899
 
 
900
 
    def onecmd(self, line, **opt):
901
 
        """catch all error and stop properly command accordingly"""
 
966
    def error_handling(self, error, line):
902
967
        
903
968
        me_dir = ''
904
969
        if hasattr(self, 'me_dir'):
905
970
            me_dir = os.path.basename(me_dir) + ' '
906
971
        
 
972
        
907
973
        try:
908
 
            return self.onecmd_orig(line, **opt)
 
974
            raise 
909
975
        except self.InvalidCmd as error:            
910
976
            if __debug__:
911
977
                self.nice_error_handling(error, line)
933
999
            if __debug__:
934
1000
                self.nice_config_error(error, line)
935
1001
            logger.error(self.keyboard_stop_msg)
 
1002
        
 
1003
 
 
1004
 
 
1005
    def onecmd(self, line, **opt):
 
1006
        """catch all error and stop properly command accordingly"""
 
1007
           
 
1008
        try:
 
1009
            return self.onecmd_orig(line, **opt)
 
1010
        except BaseException, error: 
 
1011
            self.error_handling(error, line)
 
1012
            
936
1013
    
937
1014
    def stop_on_keyboard_stop(self):
938
1015
        """action to perform to close nicely on a keyboard interupt"""