How can I uncomment “#” a line using python?

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?

• Wyh not "if...then" statement? – kilbee Oct 10 '14 at 10:34
• Can I ask why you would want to do this? – 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.

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)

t.from_string("\n".join(l))

head, tail = ntpath.split(__file__)