Reputation: 287
I am writing a program that is going to run a lot of print output. All I'm really looking to do is have certain pieces of that print output, written directly into my program after it is closes.
Think as if there were a 'save()' function the likeness of the 'print()' that would work like this:
string = "#this my generated comment"
save(string,line)
Line would of course be the line where you want the string saved into the program. Now bare in mind, I don't just want to be limited to adding comments, I would like code that will execute the next time that new line is called.
If the only way to do this is to save the file, edit it and then reload, that is fine. A basic walk-through would be greatly appreciated,
Edit: Alternatively, I am not opposed to the idea of saving the added line into another file and then importing it from the program.
thanks,
Upvotes: 1
Views: 90
Reputation: 891
The commenters stating that it is bad form / poor practice to modify a python program on the fly are arguably very wrong. This is one of the main features of python which I have personally used on numerous occasions (as a CS grad student working on PL theory). They are however correct that it is bad form to do meta-programming using strings like "x = x + 1". If you want to change the operation of your program on the fly you should use the type function. Also take a look at the following tutorial on meta-programming in python:
http://python-3-patterns-idioms-test.readthedocs.org/en/latest/Metaprogramming.html
If you really need to save an instance of one of your classes across runs of the program, then you would use the pickle library as James Mills pointed out in his answer. It's as simple as:
#!/usr/bin/python
class HelloWorld:
def __init__(self, string):
self.string = string
def run(self):
print self.string
import pickle
pickle.dump(HelloWorld, open("prog.pkl", 'w'))
HW = pickle.load(open("prog.pkl", 'r'))
x = HW("Hello World")
x.run()
Edit: In order to have "code that will execute the next time that new line is called" you don't want to use inspect.getsource()
, instead you should (following the above code):
import types
def newfncn(self):
print self.string + " 2.0!"
x.run = types.MethodType(newfncn, x)
x.run()
If you really must use strings to edit your code, you can do something like:
import types
def newfncn(self):
exec("print self.string + \" 2.0!\"")
x.run = types.MethodType(newfncn, x)
x.run()
Which I highly advise against.
Upvotes: 1
Reputation: 19040
Rather than trying to modify the source code of your running module/program consider any of the following:
Some helpful links:
Upvotes: 3