简体   繁体   中英

Writing to config.py file from another python script

I've created a python script that reads from a config.py file using import config to inform it's output.

config.py :

current_brightness = 0

script.py :

import config

set_brightness(config.current_brightness + 1)

I need current_brightness to be permanently incremented in config.py after running the script, so that subsequent script runs will import the newly updated value instead of it always being 0.

In other words, how do I write to a config.py file like I would any other standard config format like config.ini ?

You will need to persist the data somewhere on the hard disk. Two ways to go about it would be

  1. database
  2. file

database would be an overkill for storing just a number.

store the number in a file, programmatically read it using open() , programmatically update the value and write back the value into the file

Checkout this for more info on file I/O

My suggestion is to use classAttributes While running the program, you can define the settings you need as an attribute and use them

config.py

class Config:
current_brightness = 0 # define config attribute

and for use in script.py

Config.current_brightness +=1
# ....
print(Config.current_brightness) # return new value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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