这是我的挑战。我有一个radioConfig.py文件,其中包含需要更改的变量值,如果和当用户更改位置或扫描时间。这将与学生一起使用,所以我正在编程一个GUI, pysimplegui,来改变这些变量的值。
这是我到目前为止,但它不工作。它替换的是变量名,而不是值。
我正在使用Rpi和python3。我学的是电子学,我的编程技能是c语言。我不确定这是否是解决我的挑战的最佳方法,也不知道存在哪些有用的python选项。如果你能帮我,那就太好了。
#File: GuiTest.py before code is executed
freqCenter = 21000000
freqBandwidth = 8000000
upconvFreqHz = 125000000
fftWindow = "BlacHarr"
notes = "Test"
rtlSampleRateHz = 2000000
#-----------------------------------------------------------------------
#Program which will be a gui asking user for input values
freqCenterGUI = 20800280
with open('GuiTest.py', 'r') as file :
filedata = file.read()
filedata = filedata.replace('freqCenter', str(freqCenterGUI).strip('()'))
with open('GuiTest.py', 'w') as file:
file.write(filedata)
#File: GuiTest.py after code is executed
20800280 = 21000000
freqBandwidth = 8000000
upconvFreqHz = 125000000
notes = "Test"
rtlSampleRateHz = 2000000
#-----------------------------------------------------------------------
我会说:使用配置文件
修改脚本真的不是一个好习惯!
在你的cfg.ini中:
[_]
freqCenter = 21000000
freqBandwidth = 8000000
upconvFreqHz = 125000000
fftWindow = BlacHarr
notes = Test
rtlSampleRateHz = 2000000
然后使用configparser:
import configparser
cfg = configparser.ConfigParser()
with open('cfg.ini', encoding='utf-8') as f:
cfg.read_file(f)
cfg['_']['freqCenter'] = '20800280'
with open('cfg.ini', 'w', encoding='utf-8') as f:
cfg.write(f)
编辑:
或者,就像@juanpa建议的那样。Arrivillaga,使用json也是一个很好的解决方案!
品味问题…:)
又快又脏:
文件1:
freqCenter = 21000000
freqBandwidth = 8000000
upconvFreqHz = 125000000
fftWindow = "BlacHarr"
notes = "Test"
rtlSampleRateHz = 2000000
文件2
#Program which will be a gui asking user for input values
freqCenterGUI = "20800280"
my_dict={}
file_data=open("GuiTest.py", "r")
in_lines=file_data.readlines()
for line in in_lines:
var, val = line.split('=')
if var.strip() == "freqCenter":
val = freqCenterGUI + "n"
my_dict[var]=val
f_out=open("GuiTest.py", "w")
for key,val in my_dict.items():
f_out.write(str(key)+"="+str(val))
f_out.close()