This question already has answers here:
Parse key value pairs in a text file
(7 answers)
Closed 1 year ago.
I'm using a config file to inform my Python script of a few key-values, for use in authenticating the user against a website.
I have three variables: the URL, the user name, and the API token.
I've created a config file with each key on a different line, so:
url:<url string>
auth_user:<user name>
auth_token:<API token>
I want to be able to extract the text after the key words into variables, also stripping any "\n" that exist at the end of the line. Currently I'm doing this, and it works but seems clumsy:
with open(argv[1], mode='r') as config_file:
lines = config_file.readlines()
for line in lines:
url_match = match('jira_url:', line)
if url_match:
jira_url = line[9:].split("\n")[0]
user_match = match('auth_user:', line)
if user_match:
auth_user = line[10:].split("\n")[0]
token_match = match('auth_token', line)
if token_match:
auth_token = line[11:].split("\n")[0]
Can anybody suggest a more elegant solution? Specifically it's the ... = line[10:].split("\n")[0] lines that seem clunky to me.
I'm also slightly confused why I can't reuse my match object within the for loop, and have to create new match objects for each config item.
you could use a .yml file and read values with yaml.load() function:
import yaml
with open('settings.yml') as file:
settings = yaml.load(file, Loader=yaml.FullLoader)
now you can access elements like settings["url"] and so on
If the format is always <tag>:<value> you can easily parse it by splitting the line at the colon and filling up a custom dictionary:
config_file = open(filename,"r")
lines = config_file.readlines()
config_file.close()
settings = dict()
for l in lines:
elements = l[:-1].split(':')
settings[elements[0]] = ':'.join(elements[1:])
So, you get a dictionary that has the tags as keys and the values as values. You can then just refer to these dictionary entries in your pogram.
(e.g.: if you need the auth_token, just call settings["auth_token"]
if you can add 1 line for config file, configparser is good choice
https://docs.python.org/3/library/configparser.html
[1] config file : 1.cfg
[DEFAULT] # configparser's config file need section name
url:<url string>
auth_user:<user name>
auth_token:<API token>
[2] python scripts
import configparser
config = configparser.ConfigParser()
config.read('1.cfg')
print(config.get('DEFAULT','url'))
print(config.get('DEFAULT','auth_user'))
print(config.get('DEFAULT','auth_token'))
[3] output
<url string>
<user name>
<API token>
also configparser's methods is useful
whey you can't guarantee config file is always complete
You have a couple of great answers already, but I wanted to step back and provide some guidance on how you might approach these problems in the future. Getting quick answers sometimes prevents you from understanding how those people knew about the answers in the first place.
When you zoom out, the first thing that strikes me is that your task is to provide config, using a file, to your program. Software has the remarkable property of solve-once, use-anywhere. Config files have been a problem worth solving for at least 40 years, so you can bet your bottom dollar you don't need to solve this yourself. And already-solved means someone has already figured out all the little off-by-one and edge-case dramas like stripping line endings and dealing with expected input. The challenge of course, is knowing what solution already exists. If you haven't spent 40 years peeling back the covers of computers to see how they tick, it's difficult to "just know". So you might have a poke around on Google for "config file format" or something.
That would lead you to one of the most prevalent config file systems on the planet - the INI file. Just as useful now as it was 30 years ago, and as a bonus, looks not too dissimilar to your example config file. Then you might search for "read INI file in Python" or something, and come across configparser and you're basically done.
Or you might see that sometime in the last 30 years, YAML became the more trendy option, and wouldn't you know it, PyYAML will do most of the work for you.
But none of this gets you any better at using Python to extract from text files in general. So zooming in a bit, you want to know how to extract parts of lines in a text file. Again, this problem is an age-old problem, and if you were to learn about this problem (rather than just be handed the solution), you would learn that this is called parsing and often involves tokenisation. If you do some research on, say "parsing a text file in python" for example, you would learn about the general techniques that work regardless of the language, such as looping over lines and splitting each one in turn.
Zooming in one more step closer, you're looking to strip the new line off the end of the string so it doesn't get included in your value. Once again, this ain't a new problem, and with the right keywords you could dig up the well-trodden solutions. This is often called "chomping" or "stripping", and with some careful search terms, you'd find rstrip() and friends, and not have to do awkward things like splitting on the '\n' character.
Your final question is about re-using the match object. This is much harder to research. But again, the "solution" wont necessarily show you where you went wrong. What you need to keep in mind is that the statements in the for loop are sequential. To think them through you should literally execute them in your mind, one after one, and imagine what's happening. Each time you call match, it either returns None or a Match object. You never use the object, except to check for truthiness in the if statement. And next time you call match, you do so with different arguments so you get a new Match object (or None). Therefore, you don't need to keep the object around at all. You can simply do:
if match('jira_url:', line):
jira_url = line[9:].split("\n")[0]
if match('auth_user:', line):
auth_user = line[10:].split("\n")[0]
and so on. Not only that, if the first if triggered then you don't need to bother calling match again - it will certainly not trigger any of other matches for the same line. So you could do:
if match('jira_url:', line):
jira_url = line[9:].rstrip()
elif match('auth_user:', line):
auth_user = line[10:].rstrip()
and so on.
But then you can start to think - why bother doing all these matches on the colon, only to then manually split the string at the colon afterwards? You could just do:
tokens = line.rstrip().split(':')
if token[0] == 'jira_url':
jira_url = token[1]
elif token[0] == 'auth_user':
auth_user = token[1]
If you keep making these improvements (and there's lots more to make!), eventually you'll end up re-writing configparse, but at least you'll have learned why it's often a good idea to use an existing library where practical!
When I create a new document with python-docx and add paragraphs, it starts at the very first line. But if I use an empty document (I need it because of the user defined styles) and add paragraphes the document would always start with an empty line. Is there any workaround?
You can call document._body.clear_content() before adding the first paragraph.
document = Document('my-document.docx')
document._body.clear_content()
# start adding new paragraphs and whatever ...
That will leave the document with no paragraphs, so when you add new ones they start at the beginning.
It does, however, leave the document in a technically invalid state. So if you didn't add any new paragraphs and then tried to open it with Word, you might get a repair error on loading.
But if the next thing you're doing is adding paragraphs of your own, this should work just fine.
Also, note that this is technically an "internal" method and is not part of the documented API. So there's no guarantee this method's name won't change in a future release. But frankly I can't see any reason to change or remove it, so I expect it's safe enough :)
Motivation: I was going around assigning parameters read in from a config file to variables in a function like so:
john = my_quest
terry = my_fav_color
eric = airspeed
ni = swallow_type
...
when I realized this was going to be a lot of parameters to pass. I thus decided I'd put these parameters in a nice dictionary, grail, e.g. grail['my_quest'] so that the only thing I needed to pass to the function was grail.
Question: Is there a simple way in Sublime (or Notepad++, Spyder, Pycharm, etc.) to paste grails['variable'] around those variables in one step, instead of needing to paste the front and back seperately? (I know about multiple cursors in Sublime, that does help, but I'd love to find a "highlight-variable-and-hit-ctrl-meta-shift-\" and it's done.)
Based on examples you provided, this is a simple task solvable using standard regex find/replace.
So in Notepad++, record this macro (for recording control examine Macro menu):
Press Ctrl+H to open Find/Replace dialog
Find what: = (.*)$
Replace with: = grail['\1']
Choose Regular Expression and press Replace All
If you finish recording the macro and you choose to save it, shortcut key is requested. Assign your favorite ctrl-meta-shift-\ and you are done.
I have this object in Mongo:
mystuff = ListField(ReferenceField(Asset, dbref=True))
I have a Python method that is supposed to update the Mongo object, prepending its mystuff Listfield value with a given value. Because Mongoengine doesn't yet have a way to insert an object into a certain point in a list (and has made it a low priority to add this function), I've tried to:
save the contents of the current list to a temporary variable (oldlist)
update the DB entry, emptying the mystuff list using the "pull_all" modifier (which is part of mongoengine)
update the DB entry again, pushing the newly added item to the mystuff list using update(push)
update the DB entry once again, using the "push_all" modifier and the oldlist variable to push the old stuff back onto the mystuff list.
It seems that "pull_all" requires some kind of modifier, but I'll be danged if I can figure out what it wants.
Anybody got any ideas? Of course the ideal situation would be to add an "insert_at" modifier to update(), but that's out of my hands. Life on the edge, etc.
The pull_all takes a list of elements you want to pull out of the list. In you're case I believe this will be oldlist.
However I think you're best bet is probably to retrieve the whole document with get, modify the mystuff field in the client code, and send it back with a save.
As you noted the tools for updating the document in place are limited.
im building a test program. its essentially a database of bugs and bug fixes. it may end up being an entire database for all my time working in python.
i want to create an effect of layers by using a dictionary.
here is the code as of april 29 2011:
modules=['pass']
syntax={'PRINT':''' in eclipse anthing which
you "PRINT" needs to be within a set of paranthesis''','StrRet':'anytime you need to use the return action in a string, you must use the triple quotes.'}
findinp= input('''where would you like to go?
Dir:''')
if findinp=='syntax':
print(syntax)
dir2= input('choose a listing')
if dir2=='print'or'PRINT'or'Print':
print('PRINT' in syntax)
now when i use this i get the ENTIRE dictionary, not just the first layer. how would i do something like this? do i need to just list links in the console? or is there a better way to do so?
thanks,
Pre.Shu.
I'm not quite sure what you want, but to print the content of a single key of dictionary you index it:
syntax['PRINT']
Maybe this help a bit:
modules=['pass']
syntax={
'PRINT':''' in eclipse anthing which
you "PRINT" needs to be within a set of paranthesis''',
'STRRET':'anytime you need to use the return action in a string, you must use the triple quotes.'}
choice = input('''where would you like to go?
Dir:''').upper()
if choice in syntax:
print syntax[choice]
else:
print "no data ..."