I would like to use a txt file with configure variable for my python code.And I saw and copied following code from web to my python.
def getVarFromFile(filename):
import imp
f = open(filename)
global cs
cs = imp.load_source('cs', '', f)
f.close()
The strange thing is whenever I run the python code, I got a file named "c" in my directory, and it stores lots of strange characters like:
mò ;€-Rc
Why there comes this "c" file ? How can I get rid of that ? Thanks
----adding info----- I made the call by
getVarFromFile('config/cs.txt')
And my cs.txt looks like:
var1 = 'abc'
var2 = 'h'
var3 = '2'
var4 = '1'
And I use the data like:
var2 = int(cs.var2)
And by my debugging, once I put the
sys.exit()
Before
cs = imp.load_source('cs', '', f)
There is no such c file is generated. While I put exit after that line, there is the file named "c" generated.
So it must relate to that function
You need to give a more sensible value for the pathname parameter.
imp.load_source(name, pathname, file) is used to load a sourcefile. As part of that it will compile the sourcefile to bytecode and write the compiled code out to a .pyc file. The name of the .pyc file I think it gets by putting c on the end of the pathname you supplied.
If you don't want the compile caching, then simply read the file and create your own module. See Load module from string in python for a way to do this:
import sys,imp
my_code = 'a = 5'
mymodule = imp.new_module('mymodule')
exec my_code in mymodule.__dict__
Combined with your original code would be something like (untested):
def getVarFromFile(filename):
import imp
with open(filename) as f:
global cs
cs = imp.new_module('cs')
exec(f.read(), cs.__dict__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With