简体   繁体   English

如何从python脚本更改python文件中的变量值

[英]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.

相关问题 如何从另一个文件更改python文件的变量值? - How to change value of a variable of a python file from another file? 如何从另一个python脚本更改一个python脚本中变量的值 - How to change value of the variable in one python script from another python script 如何从Python中的其他文件更改函数中变量的值? - How to change the value of a variable in a function from a different file in Python? 如何在Python中从其他.py文件更改变量的值 - How to change value of variable from a different .py file in Python 有没有办法从javascript更改python脚本中变量的值? - Is there way to change the value of a variable in a python script from javascript? 如何将变量值从 Python 脚本传输到 Bash 脚本 - How to transfer variable value from Python script to a Bash script 如何使用可执行的Linux程序/脚本更改python文件中的变量? - How to change variable in python file using an executable linux program/script? 如何使用 python 脚本更改 vti 文件中的字段变量/单元格值 - how to change field variable/cell values in vti file with python script 如何从网页上更改正在运行的Python脚本/服务中的变量? - How to change a variable in a running Python script/service from a web page? 从脚本python获取变量环境的更改 - Get change of variable environment from script python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM