Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

Copying and pasting code into the Python interpreter

There is a snippet of code that I would like to copy and paste into my Python interpreter. Unfortunately due to Python's sensitivity to whitespace it is not straightforward to copy and paste it a way that makes sense. (I think the whitespace gets mangled) Is there a better way? Maybe I can load the snippet from a file.

This is just an small example but if there is a lot of code I would like to avoid typing everything from the definition of the function or copy and pasting line by line.

class bcolors: 
    HEADER = '33[95m' 
    OKBLUE = '33[94m' 
    OKGREEN = '33[92m' 
    WARNING = '33[93m' 
    FAIL = '33[91m' 
    ENDC = '33[0m' 

    def disable(self):  
        self.HEADER = '' # I think stuff gets mangled because of the extra level of indentation 
        self.OKBLUE = '' 
        self.OKGREEN = '' 
        self.WARNING = '' 
        self.FAIL = '' 
        self.ENDC = ''
question from:https://stackoverflow.com/questions/2501208/copying-and-pasting-code-into-the-python-interpreter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can call execfile(filename). More or less the same as importing a module, except that it skips the module administration part and doesn't require you to add a folder to sys.path.

EDIT: To address the original question: copy-pasted code can be executed by calling exec(codestring).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...