ConfigParser - Create file if it doesn't exist - python

So I am working on creating a program in Python that reads a .ini file to set up some boot variables for the main program. My only thing is, I want the program on initialization, to check if the .ini file exists, and if it doesn't, create it with a set of default values. Kind of a preemptive bug fix on if someone accidentally deletes the file.
I can't seem to find any examples anywhere of how to do this, and I'm not super experienced with Python (only been programming with it for about a week) so I'd appreciate any assistance :)
Edit: Upon further thought, I want to pursue this a bit further.
Let's assume the file does exist. How do I check it to make sure it has the appropriate sections? If it doesn't have the appropriate sections, how would I go about deleting the file or removing the contents and rewriting the contents of the file?
I'm trying to idiot proof this :P

You can use ConfigParser and the OS library, here's a quick example:
#!usr/bin/python
import configparser, os
config = configparser.ConfigParser()
# Just a small function to write the file
def write_file():
config.write(open('config.ini', 'w'))
if not os.path.exists('config.ini'):
config['testing'] = {'test': '45', 'test2': 'yes'}
write_file()
else:
# Read File
config.read('config.ini')
# Get the list of sections
print config.sections()
# Print value at test2
print config.get('testing', 'test2')
# Check if file has section
try:
config.get('testing', 'test3')
# If it doesn't i.e. An exception was raised
except configparser.NoOptionError:
print "NO OPTION CALLED TEST 3"
# Delete this section, you can also use config.remove_option
# config.remove_section('testing')
config.remove_option('testing', 'test2')
write_file()
Output:
[DEFAULT]
test = 45
test2 = yes
Linked above are the docs that are extremely useful to learn more about writing configuration files and other in-built modules.
Note: I'm kind of new to python, so if anyone knows a better approach let me know I'll edit my answer!

Related

Python - How to call code from an external file

I have revised this question to make it much more simple.
I am running a program in python 3.x.
I want this program to open a file name example.py and run the code inside it.
This is the contents of the file:
#example1.py
print('hello world')
#example2.py
print('hello world 2')
#main.py
someMagicalCodeHere(executes example2.py)
#prints hello world
I need to do this without it being an imported file.
The problem with imported files is they are declared beforehand in the main.py. My main.py will be creating example1.py, example2.py etc and filling them with code, and then later referencing back to them as needed. There may be thousands or millions.
This is part of a large project that we are trying to switch over to a new language. We don't know python yet, and we need this concept to be viable to continue learning the language.
I have tried
exec(example.py)
I have tried
with open('example.py', 'r') as ex:
ex.read()
Thanks in advance for the answer, and thanks for all who have answered thus far.
I'm assuming you have some kind of a function that converts strings to such answers, or perhaps a dictionary. Otherwise the solution to this problem would be beyond the scope of current progress in NLP.
def ask_question_and_get_response(question=None):
answer = input(question)
return answer
I must also assume that you have a way to convert the original question, such as "What is your name?", to one that the user may in turn ask your bot, "What is my name?". Let that function look like what follows:
def get_reflex_question(question):
<your implementation>
return reflex_question
With both of these in hand, we can create a file (if one doesn't already exist), and write what can be interpreted as Python code to it.
def make_code(answer, reflex_question)
with open("filename", "a") as file:
file.write("\n")
file.write("if userBoxAsks == %s:\n\t" % (reflex_question))
file.write("print(answer)")
Which will output code to a file of your naming.
To run that file, you could use the subprocess module (read documentation), or simply import this file of yours as a module itself.
Whenever you update the file, you could reload the import so that the new code runs too. In Python3.x, you can do importlib.reload(filename) to refresh the import.
Alright after much deliberation, hunting and searching, I discovered through experimentation, found the answer to my own question.
#c:\\one.py
print('hello world')
#c:\\main.py
import os.path
filename = "c:\\one.py"
if not os.path.isfile(filename):
print ('File does not exist.')
else:
with open(filename) as f:
content = f.read().splitlines()
for line in content:
exec(line)
Returns (without quotes) 'Hello World'
Note that these solutions are not secure and considered risky. So obviously meant for play/test purpose
Python 2:
execfile('example2.py')
Python 3:
with open('example2.py') as f:
exec(f.read())

Python variable value from separate file?

I have a Python script that runs 24hrs a day.
A module from this script is using variables values that I wish to change from time to time, without having to stop the script, edit the module file, then launch the script again (I need to avoid interruptions as much as I can).
I thought about storing the variables in a separate file, and the module would, when needed, fetch the new values from the file and use them.
Pickle seemed a solution but is not human readable and therefore not easily changeable. Maybe a JSON file, or another .py file I import over again ?
Another advantage of doing so, for me, is that in case of interruption (eg. server restart), I can resume the script with the latest variable values if I load them from a separate file.
Is there a recommended way of doing such things ?
Something along the lines :
# variables file:
variable1 = 10
variable2 = 25
# main file:
while True:
import variables
print('Sum:', str(variable1+variable2))
time.sleep(60)
An easy way to maintain a text file with variables would be the YAML format. This answer explains how to use it, basically:
import yaml
stream = open("vars.yaml", "r")
docs = yaml.load_all(stream)
If you have more than a few variables, it may be good to check the file descriptor to see if the file was recently updated, and only re-load variables when there was a change in the file.
import os
last_updated = os.path.getmtime('vars.yaml')
Finally, since you want avoid interruption of the script, it may be good to have the script catch any errors in the YAML file and warn the user, instead of just throwing an exception and die. But also remember that "errors should never pass silently". What is the best approach here would depend on your use-case.

Running Fortran executable within Python script

I am writing a Python script with the following objectives:
Starting from current working directory, change directory to child directory 'A'
Make slight adjustments to a fort.4 file
Run a Fortran binary file (the syntax of which is ../../../../ continuing until I hit the folder containing the binary); return to 2. until my particular objective is complete, then
Back out of child directory to parent, then enter another child directory and return to 2. until I have iterated through all the folders in question.
The code is coming along well. I am having to rely heavily upon Python's OS module for the directory work. However, I have never had any experience a) making minor adjustments of a file using python and b) running an executable. Could you guys give me some ideas on Python modules, direct me to a similar stack source etc, or perhaps give ways that this can be accomplished? I understand this is a vague question, so please ask if you do not understand what I am asking and I will elaborate. Also, the changes I have to make to this fort.4 file are repetitive in nature; they all happen at the same position in the file.
Cheers
EDIT::
entire fort.4 file:
file_name
movie1.dat !name of a general file the binary reads
nbr_box ! line3-8 is general info
2
this_box
1
lrdf_bead
.true.
beadid1
C1 !this is the line I must change
beadid2
F4 !This is a second line I must change
lrdf_com
.false.
bin_width
0.04
rcut
7
So really, I need to change "C1" to "C2" for example. The changes are very insignificant to make, but I must emphasize the fact that the main fortran executable reads this fort.4, as well as this movie1.dat file that I have already created. Hope this helps
Ok so there is a few important things here, first we need to be able to manage our cwd, for that we will use the os module
import os
whenever a method operates on a folder it is important to change directories into the folder and back to the parent folder. This can also be achieved with the os module.
def operateOnFolder(folder):
os.chdir(folder)
...
os.chdir("..")
Now we need to do some method for each directory, that comes with this,
for k in os.listdir(".") if os.path.isdir(k):
operateOnFolder(k)
Finally in order to operate on some preexisting FORTRAN file we can use the builtin file operators.
fileSource = open("someFile.f","r")
fileText = fileSource.read()
fileSource.close()
fileLines = fileText.split("\n")
# change a line in the file with -> fileLines[42] = "the 42nd line"
fileText = "\n".join(fileLines)
fileOutput = open("someFile.f","w")
fileOutput.write(fileText)
You can create and run your executable output.fx from source.f90::
subprocess.call(["gfortran","-o","output.fx","source.f90"])#create
subprocess.call(["output.fx"]) #execute

Suitable ways to store python script configurations

I have an python script that needs to be run in the Windows cmd.exe for some testing, it has three options to choose
such as
config A
config B
config C
Hence the user can choose different config by running xx.py configA, the script will use the config A as options until the user specify another config.
Due to some reasons, my program does not use for loop to keep track of the state of the config, hence I have three options to choose based on my research
Delete A single file that A use, but B C does not, and similar process is done with B and C (config A, B and C will use difference executable file to run the same things)
sample code like this:
if os.environ.get('xx'):
path_a = os.path.join('xx','xx.dll')
if os.path.isfile(path_a):
os.remove(path_a)
2.Another idea is to use a local file to keep track of the configuration by checking the specific text in the text file and decide which executable file to choose
3.Third idea is to create an registry key for this script and keep track of that
My question is which way should I go with and is any other better way I can achieve the same results.
From what I can understand you are asking the following:
What is the best way for my python script to handle running with one of three different arguments that points to the configuration settings to use during that run.
If that is the case, then I think you should look into xml.etree as an option to store and access configuration data in a config file. you should only need 1 config file this way since you can utilize different nodes with configuration settings as children for each config option.
you could save your configuration in a file in this format;
<configroot>
<configsettings1>
<option1>foo</option1>
<option2>bar</option2>
</configsettings1>
<configsettings2>
<option1>foo</option1>
<option2>foo</option2>
and so on. you can even customize it a bit more by adding more data to each option:
<option1 disabled=True>
or
<option2 active=1 type='foo'>
then you can extract the nodes from that depending on what args are used with getopt
import getopt
import xml.etree as et
INSERTMAINCODEHERE
if __name__ == '__main__':
try:
opts, args = getopt.getopt(sys.argv[1:], "f:", ["configoption="])
except getopt.GetoptError, e:
print "getopt.GetoptError: %s" % e
sys.exit(1)
for o, a in opts:
if o in ("-f","--configoption="):
b=et.ElementTree.parse('configfilename')
options=b.getroot().find(a)
for s in list(options):
print s, s.tag, s.tail, s.attrib #ETC. ETC.
you can see more information and some detail about the specifics here
I hope this is what you were asking. if not please let me know more and I'll try to help.

Python: how to input python-code part like \input in Tex?

I want to input code in Python like \input{Sources/file.tex}. How can I do it in Python?
[added]
Suppose I want to input data to: print("My data is here"+<input data here>).
Data
1, 3, 5, 5, 6
The built-in execfile function does what you ask, for example:
filename = "Sources/file.py"
execfile( filename )
This will execute the code from Sources/file.py almost as if that code were embedded in the current file, and is thus very similar to #include in C or \input in LaTeX.
Note that execfile also permits two optional arguments allowing you to specify the globals and locals dicts that the code should be executed with respect to, but in most cases this is not necessary. See pydoc execfile for details.
There are occasional legitimate reasons to want to use execfile. However, for the purpose of structuring large Python programs, it is conventional to separate your code into modules placed somewhere in the PYTHONPATH and to load them using the import statement rather than executing them with execfile. The advantages of import over execfile include:
Imported functions get qualified with the name of the module, e.g. module.myfunction instead of just myfunction.
Your code doesn't need to hard-code where in the filesystem the file is located.
You can't do that in Python. You can import objects from other modules.
otherfile.py:
def print_hello():
print "Hello World!"
main.py
import otherfile
otherfile.print_hello() # prints Hello World!
See the python tutorial
Say you have code in "my_file.py". Any line which is not in a method WILL get executed when you do:
import my_file
So for example if my_file.py has the following code in it:
print "hello"
Then in the interpreter you type:
import my_file
You will see "hello".
My question was clearly too broad, as the variety of replies hint -- none of them fully attack the question. The jchl targets the scenario where you get python-code to be executed. The THC4k addresses the situation where you want to use outside objects from modules. muckabout's reply is bad practice, as Xavier Ho mentioned, why on earth it uses import when it could use exec as well, the principle of least privileges to the dogs. One thing is still missing, probably because of the conflict between the term python-code in the title and the addition of data containing integers -- it is hard to claim that data is python-code but the code explains how to input data, evaluations and executable code.
#!/usr/bin/python
#
# Description: it works like the input -thing in Tex,
# you can fetch outside executable code, data or anything you like.
# Sorry I don't know precisely how input(things) works, maybe misusing terms
# or exaggerating.
#
# The reason why I wanted input -style thing is because I wanted to use more
# Python to write my lab-reports. Now, I don't need to mess data with
# executions and evalutions and data can be in clean files.
#TRIAL 1: Execution and Evaluation not from a file
executeMe="print('hello'); a = 'If you see me, it works'";
exec( executeMe )
print(a);
#TRIAL 2: printing file content
#
# and now with files
#
# $ cat IwillPrint007fromFile
# 007
f = open('./IwillPrint007fromFile', 'r');
msg = f.read()
print("If 007 == " + msg + " it works!");
# TRIAL 3: Evaluation from a file
#
# $cat IwillEvaluateSthing.py
# #!/usr/bin/python
# #
# # Description:
#
#
# evaluateMe = "If you see me again, you are breaking the rules of Sky."
f = open('./IwillEvaluateSthing.py', 'r');
exec(f.read());
print(evaluateMe);

Categories

Resources