我試圖從SPICE網表文件中提取數據,具體是定義的參數。這是內容的文件「netlist.sp」的(利息):如何在同一個函數中使用從字符串創建的全局變量?
.param freq = 860x powS = 0
+ pi = 3.141592
+ nper = 15 cap1 = 68p
+ cycles = 20
+ tper = '1/freq'
+ tstep = 'tper/nper'
+ tstop = 'cycles*tper'
僅供參考,+
號表示繼續前行,而param = 'equation'
計算表達式。
所以,我想在每個參數的Python 3.6中創建一個全局變量。這是我到目前爲止的代碼:
def isnumber(s):
try:
float(s)
return True
except ValueError:
return False
#This function is needed to convert the '68p' format to '68e-12'
def floatify(st):
if not isnumber(st[-1]):
vals = [ 't', 'g', 'x', 'meg', 'k', 'm', 'u', 'n', 'p', 'f', 'a']
prod = [1e12, 1e9, 1e6, 1e6, 1e3, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18]
pos = vals.index(st[-1])
st = st[:-1]
num = float(st) * prod[pos]
else:
num = float(st)
return num
#This is the main function
def params (file):
fl = 0
strng = '00'
tnum = 0.0
with open(file) as dat:
for line in dat:
if line.startswith('*'):
pass
elif line.startswith('.param '):
fl = 1
spl = line.split()
a = [i for i,x in enumerate(spl) if x=='=']
for i in range(len(a)):
strng = spl[a[i]-1]
try:
tnum = floatify(spl[a[i]+1])
except ValueError:
tnum = eval(spl[a[i]+1])
globals()[strng] = tnum
elif (line.find('+')+1) and fl:
spl = line.split()
a = [i for i,x in enumerate(spl) if x=='=']
for i in range(len(a)):
strng = spl[a[i]-1]
try:
tnum = floatify(spl[a[i]+1])
except ValueError:
temp = spl[a[i]+1]
tnum = eval(temp)
globals()[strng] = tnum
elif (not (line.find('+')+1)) and fl:
break
params('netlist.sp')
#Testing the variables
print('params done')
print('freq = ', freq)
print('powS = ', powS)
print('pi = ', pi)
print('nper = ', nper)
print('cap1 = ', cap1)
print('cycles = ', cycles)
print('tper = ', tper)
print('tstep = ', tstep)
print('tstop = ', tstop)
# Testing the eval function:
print(eval('1/freq'))
print(eval('2*pi'))
的globals()[strng] = tnum
語句創建從已提取的字符串的全局變量,並分配相應的值。
輸出是:
freq = 860000000.0
powS = 0.0
pi = 3.141592
nper = 15.0
cap1 = 6.8e-11
cycles = 20.0
tper = 1/freq
tstep = tper/nper
tstop = cycles*tper
1.1627906976744186e-09
6.283184
所以,我從eval
功能的測試不解的是,params
函數內部創建的全局變量只能在外面的功能本身的理解。我知道要修改函數內的全局變量,你必須在函數中聲明global var
語句。我的問題是如何在這種情況下做到這一點,當變量動態創建?
爲什麼不只是製作一個'params = {}'字典,然後用你想要的任何東西來填充它,並使用'global params'來訪問它的函數。 – TemporalWolf
是的,我想過使用字典,但使用'eval'函數來提取由表達式定義的參數值將會變得更加複雜。 –
你不必評估它們,這就是要點。從查看你的代碼,你會過度複雜化整個事情。 – TemporalWolf