简体   繁体   English

Python:有没有办法永久更改另一个 Python 文件中的变量?

[英]Python: is there a way to permanently change a variable from another Python file?

Is there a way to permanently change a variable, so it does not reset when the code finishes?有没有办法永久更改变量,所以代码完成时它不会重置? I have this code:我有这个代码:

variables.py:变量.py:

myvar = None

Main.py:主要.py:

import variables
variables.myvar = True

Get_variable.py:获取变量.py:

import variables
print(variables.myvar)

Output: Output:

None

I want it to print True我希望它打印True

I don't believe it's possible (without re-writing the entire python script in the second script to write the entire thing back to file), but there's another way to do this.我不相信这是可能的(无需在第二个脚本中重写整个 python 脚本以将整个内容写回文件),但还有另一种方法可以做到这一点。 Instead of storing variables in a python script, you can store variables in another type of file, like a json.您可以将变量存储在另一种类型的文件中,例如 json,而不是将变量存储在 python 脚本中。 You could have "variables.json":你可以有“variables.json”:

{ "myvar": null }

then in your python:然后在你的 python 中:

import json         # import the json library

with open("variables.json", "r") as f:      # read the json file
  variables = json.load(f)

myvar = variables["myvar"]    # To get the value currently stored

variables["myvar"] = True    # change the variable in python

with open("variables.json", "w") as f:      # write back to the json file
  json.dump(variables, f)

If you have a lot of variables, you can store them all in json as with a dictionary:如果您有很多变量,您可以将它们全部存储在 json 中,就像使用字典一样:

{ "onevar": null,
  "twovar": "kittens",
  "redvar": "foo",
  "bluevar": "bar" }

FOR OPENOFFICE WRITER: Since you're writing all of this in OpenOffice on a Raspberry pi, and having trouble creating the json file yourself (open office assumes it's a writer document), you can simply allow python to create it:对于 OPENOFFICE WRITER:由于您是在 Raspberry pi 上的 OpenOffice 中编写所有这些内容,并且在自己创建 json 文件时遇到了麻烦(open office 假定它是一个编写器文档),您可以简单地允许 python 创建它:

import json

variables = { "onevar": null,
              "twovar": "kittens",
              "redvar": "foo",
             "bluevar": "bar" }

with open("variables.json", "w") as f:
  json.dump(variables, f)

If python is told to open a file to write, and the file doesn't exist, python should create the file in question, unless it's told to create it in a directory that doesn't exist (so, you couldn't say open("myfolder/variables.json", "w") if the directory "myfolder" didn't exist).如果 python 被告知打开要写入的文件,并且该文件不存在,则 python 应该创建有问题的文件,除非它被告知在不存在的目录中创建它(所以,你不能说打开("myfolder/variables.json", "w") 如果目录 "myfolder" 不存在)。 You can run this once to init your json file, and then go on opening and closing from there.您可以运行一次以初始化 json 文件,然后从那里打开和关闭 go。

You can change the file:您可以更改文件:

fin = open("path-to-variables.txt","a")
fin.write("myvar = True")

That should change the actual file.那应该改变实际的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM