Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

convert .py to .pyc during run time to make changes take effect

Status
Not open for further replies.

TarunMakhija

Programmer
Jun 14, 2005
13
0
0
US
Hi,

I need to modify some properties that I maintain in a file called config.py.

How do I convert config.py to config.pyc programmatically during run time to ensure that the changes i made during a run time take effect.

what is happening right now is that: after i make changes to config.py during run time, the changes do not take effect. However, after i stop the application and run it again the changes i made the last time take effect.

Please let me know how to work around this.

Thanks,
Tarun
 
If you import a file the interpretter should try to compile the .py into a .pyc *if* the .py is newer than the .pyc. Does the process running have permissions to write the .pyc?
 
I tried using import config.py within the program after making changes to config.py programmatically using file.write(). The problem still remained.

Also, I am modifying the .py file (not .pyc). Have the rights to modify the .py file.

I also tried the following using the imp and codeop modules:

#write into config.py
file = open(os.path.join(os.getcwd(),"config.py"),'w')
file.write(search)
file.write("\n")
file.write("subjects=[crmTerms]")
file.close()

try:
fp, pathname, description = imp.find_module("config")
imp.load_module("config", fp, pathname, description)
codeop.compile_command("config.py")

import config
except:
print FAILED

If someone is getting where exactly I am going wrong, please let me know,

Thanks
Tarun M.
 
Have you already done an 'import config' before this code is executed?
 
Thanks :) .... For hitting the nail right on the head!
It solves my problem

I removed the import statement from all my programs which i was doing at the module level. And used them precisely where i need them :)

Its working fine now. Thanks!
Tarun M.
 
Yep, python keeps a list of imported modules so it doesn't try to import them more than once. There is a way to "re-import" a module, but it looks like you've taken care of your issues. Glad I could be of help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top