I looking for this

#My line    <=== is commented 

after running my python script

My line     <=== is uncommented 

IS there any way to get an executable code by reading a commented line?

  • 1
    $\begingroup$ Wyh not "if...then" statement? $\endgroup$ – kilbee Oct 10 '14 at 10:34
  • $\begingroup$ Can I ask why you would want to do this? $\endgroup$ – gandalf3 Oct 10 '14 at 18:54

apart from if-then clauses, no.
It's commented code for a reason, and that reason is for the interpreter to ignore it at all times.

|improve this answer|||||

Yes it is possible, but not very useful. The following naive code attempts to change line 4 of its text block within Blender. The function modify takes 4 arguments.

  • name - the file name of the script
  • lineno - the line number to change (zero based)
  • orig - the original start of the string to change
  • repl - the replacement

So if you execute the script twice, the code will be commented again. The script will attempt to find its own file name in the last 2 lines. Only tested for Linux.

import bpy
import ntpath
#this is a comment
#print("Hello Blender!") # this is code

def modify(name, lineno, orig, repl):
    t = bpy.data.texts[name]
    s = t.as_string()
    l = s.splitlines()

    if l[lineno].startswith(orig):
        l[lineno] = l[lineno].replace(orig, repl, 1)
    elif l[lineno].startswith(repl):
        l[lineno] = l[lineno].replace(repl, orig, 1)


head, tail = ntpath.split(__file__)
modify(tail or ntpath.basename(head),3,"#print","print")
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.