[英]how to change a variable value in a python file from a python script
I currently have a python file with a bunch of global variables with values. 我目前有一个python文件,其中包含一堆带有值的全局变量。 I want to change these values permanently from a separate python script.
我想从一个单独的python脚本永久更改这些值。 I've tried setattr and such but it doesnt seem to work.
我已经尝试过setattr等但它似乎没有用。 Is there a way to do this?
有没有办法做到这一点?
The short answer is: don't. 简短的回答是:不要。 It won't be worth the trouble.
这不值得麻烦。
It sounds like you are trying to create a configuration file and then have your application update it. 听起来您正在尝试创建配置文件,然后让您的应用程序更新它。 You should try using ConfigParser, a built-in module that can read and write configuration files for you with limited hassle: http://docs.python.org/library/configparser.html
您应该尝试使用ConfigParser,这是一个内置模块,可以为您轻松读取和写入配置文件: http : //docs.python.org/library/configparser.html
currently have a python file with a bunch of global variables with values
目前有一个python文件,其中包含一堆带有值的全局变量
Let's pretend it looks like this. 让我们假装它看起来像这样。
globals.py
this = 1
that = 2
And there's nothing else in this file . 此文件中没有其他内容 。 Nothing.
没有。
Let's further pretend that this file is used as follows. 让我们进一步假装这个文件使用如下。
from globals import *
Let's further pretend that we have some simulation which needs to "update" globals.py
让我们进一步假装我们有一些需要“更新”
globals.py
import os
os.rename( "globals.py", "globals.bak" )
with open( "globals.py", "w" ) as target:
for variable in ('some', 'list', 'of', 'sensible', 'globals'):
target.write( "{0!s} = {1!r}".format( variable, globals()[variable] )
Basically, you recreate Python code from your global dictionary. 基本上,您从全局字典中重新创建Python代码。
This is a dreadful solution. 这是一个可怕的解决方案。 Please don't actually use it.
请不要实际使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.