filter output of subprocess.check_output - regex

I'm trying to match values of a list to a regex pattern. If the particular value within the list matches, I'll append it to a different list of dicts. If the above mentioned value does not match, I want to remove the value from the list.
import subprocess
def list_installed():
rawlist = subprocess.check_output(['yum', 'list', 'installed']).splitlines()
#print rawlist
for each_item in rawlist:
if "[\w86]" or \
"noarch" in each_item:
print each_item #additional stuff here to append list of dicts
#i haven't done the appending part yet
#the list of dict's will be returned at end of this funct
else:
remove(each_item)
list_installed()
The end goal is to eventually be able to do something similar to:
nifty_module.tellme(installed_packages[3]['version'])
nifty_module.dosomething(installed_packages[6])
Note to gnu/linux users going wtf:
This will eventually grow into a larger sysadmin frontend.

Despite the lack of an actual question in your post, I'll make a couple of comments.
You have a problem here:
if "[\w86]" or "noarch" in each_item:
It's not interpreted the way you think of it and it always evaluates to True. You probably need
if "[\w86]" in each_item or "noarch" in each_item:
Also, I'm not sure what you are doing, but in case you expect that Python will do regex matching here: it won't. If you need that, look at re module.
remove(each_item)
I don't know how it's implemented, but it probably won't work if you expect it to remove the element from rawlist: remove won't be able to actually access the list defined inside list_installed. I'd advise to use rawlist.remove(each_item) instead, but not in this case, because you are iterating over rawlist. You need to re-think the procedure a little (create another list and append needed elements to it instead of removing, for example).

Related

How to get every combination of a combolist

I have a program where you can import a combolist, ex.
test:lol
hello:hi
sup:hey
The first one being the "username" and last one being the "password".
I want so that every single username will have a line with each password of the list. I would like all of this put into a separate string list.
Such as:
test:lol
test:hi
test:hey
hello:lol
hello:hi
hello:hey
sup:lol
sup:hi
sup:hey
I think this might be a really simple code, something to do with first separating the list into two lists, then for each username, add every password, but my brains can't really think of anything to come up with a solution for this.
thank you in advance :)
Yes, you're right.
Firs - get two lists users and passwords by separating each string by column.
Second traverse users and passwords and combine them. In pseudocode
foreach uName in users do
foreach pwd in passwords do
print user.concat(":").concat(pwd)
end
end
Explanation:
Get first `uName` from `users`
Get first `pwd` from `passwords`
output "`user`:`pwd`"
Get second `pwd` from `passwords`
output "`user`:`pwd`"
...
Get second `uName` from `users`
Get first `pwd` from `passwords`
output "`user`:`pwd`"
...
Feel free to ask, if something left unclear

Python loop with condition: using same code whether condition is met or not

I have a dict and a list:
main = {"one": "apple", "two":"pear", "three":"banana", "four":"cherry"}
conditional_list = ["one", "four"]
The conditional list may be empty or contain values (like in the case now). I would like to iterate over the dict "main". BUT: if the conditinal list is not empty, I would like to iterate only over the items that match the conditional list. So:
for key, val in mainlist:
if conditional_list:
if key in conditional_list:
do something
else:
do exactly the same thing
I it possible to set up the iteration in such a way, that I don't have to copy+paste the whole code of "do something" to "else" (the line where it says "do exactly the same thing")? Or to put it in another way: Is there a way to ignore the line "if key in conditional_list" if the condition is NOT met (i.e. the list is empty)?
The thing is, the code "do something" is huge and needs to be updated from time to time, copy+pasting it would make things extremly complicated. Thanks in advance!
What about this:
for key, val in mainlist:
if not conditional_list or key in conditional_list:
do something
My suggestion would be to pass the key to a doSomething() function
Also, you may have a reason, but it looks like the dictionary is being used backwards; given the context, this may be an apt solution for you:
for i in conditional_list:
doSomething(i,d(i),(i in mainlist))

python try-except, exception handling

I have 10 links in a list, upon clicked,which will open a new window. Different links would yield different set of pages, however i have 3 common elements for all 10 links.
Following is the function example.
def handle_window(self):
self.driver.go_to_new_window()
try: # block 1
elements = ["element1", "element2", "element3"]
for element in elements:
try: #block 2
self.assertEqual(True, is_exist_in_new_window(element)))
except:
continue
except:
# in 'try block 2' if assert yields true at least once,
print 'passed'
# if it fails for all 3 elements,
print 'failed'
self.driver.close_current_window()
self.driver.go_to_main_window()
I am not sure how do i evaluate the results of 'try block 2', so that to do some action in block 1.
Any possible solutions ?
If "element1", etc. are meant to be CSS selectors, the most efficient way would be:
elements = ["element1", "element2", "element3"]
self.assertTrue(exists_in_new_window(",".join(elements)))
(I've renamed is_exist_in_new_window to exists_in_new_window.) The , operator in CSS means "or". So the CSS selector passed to exists_in_new_window means you are looking for "element1" or "element2" or "element3". Doing it this way will need one round-trip between the Selenium client and the browser, no matter what. Note that the code above is not meant to handle meaningfully the case where elements is a zero-length list.
With XPath selectors you could use the | operator to perform a similar transformation. In this case, I would want to additionally use parentheses to preserve semantics of the individual selectors so something like "(" + ")|(".join(elements) + ")". (I believe the semantics issue does not arise in CSS due to CSS' very rigid syntax.)
In the more general case where it is not possible to combine the search criteria into one expression, one can fall back onto alecxe's suggestion:
elements = ["element1", "element2", "element3"]
self.assertTrue(any((exists_in_new_window(element) for element in elements)))
This method causes a minimum of min(1, len(elements)) round-trips between the Selenium client and the browser and a maximum of len(elements) depending on what is present on the page.
You can use any() to check if at least one element existed on a page:
elements = ["element1", "element2", "element3"]
value = any((is_exist_in_new_window(element) for element in elements))
self.assertTrue(value)
This code assumes is_exist_in_new_window() returns True or False.
Hope that helps.

For loop using enumerate through a list with an if statement to search lines for a particular string

I am going to compile a list of a recurring strings (transaction ID).
I am flummoxed. I've researched the correct method and feel like this code should work.
However, I'm doing something wrong in the second block.
This first block correctly compiles a list of the strings that I want.
I cant get this second block to work. If I simplify, I can print each value in the list
by using
for idx, val in enumerate(tidarray): print val
It seems like I should now be able to use that value to search each line for that string,
then print the line (actually I'll be using it in conjunction with another search term to
reduce the number of line reads, but this is my basic test before honing in further.
def main():
pass
samlfile= "2013-08-18 06:24:27,410 tid:5af193fdc DEBUG org.sourceid.saml20.domain.AttributeMapping] Source attributes:{SAML_AUTHN_CTX=urn:oasis:names:tc:SAML:2.0:ac:classes"
tidarray = []
for line in samlfile:
if "tid:" in line:
str=line
tid = re.search(r'(tid:.*?)(?= )', str)
if tid.group() not in tidarray:
tidarray.append(tid.group())
for line in samlfile:
for idx, val in enumerate(tidarray):
if val in line:
print line
Can someone suggest a correction for the second block of code? I recognize that reading the file twice isn't the most elegant solution... My main goal here is to learn how to enumerate through the list and use each value in the subsequent code.
Iterating over a file twice
Basically what you do is:
for line in somefile: pass # first run
for line in somefile: pass # second run
The first run will complete just fine, the second run will not run at all.
This is because the file was read until the end and there's no more data to read lines from.
Call somefile.seek(0) to go to the beginning of the file:
for line in somefile: pass # first run
somefile.seek(0)
for line in somefile: pass # second run
Storing things uniquely
Basically, what you seem to want is a way to store the IDs from the file in the a
data structure and every id shall only be once in said structure.
If you want to store elements uniquely you use, for example, dictionaries (help(dict))
or sets (help(set)). Example with sets:
myset = set()
myset.add(2) # set([2])
myset.add(3) # set([2,3])
myset.add(2) # set([2,3])

Prolog - sending a list as a parameter to be displayed

I'm trying to write a program to find a route between towns, add the path to the list and then, ad the end display it.
I think adding to the list works, but I'm having the problem displaying the list, don't know how can I pass a list as a parameter to be used when it's done finding the path? Hope you guys can help. Here's the code:
connected(middlesbrough, stockton).
connected(middlesbrough, darlington).
connected(stockton, sunderland).
connected(darlington, thirsk).
connected(stockton, newcastle).
connected(newcastle, york).
connected(thirsk, york).
connected(york, leeds).
connected(leeds, huddersfield).
connected(leeds, dewsbury).
connected(huddersfield, manchester).
connected(dewsbury, manchester).
run(List):-
write('Enter Starting City :'),
read(Start),
write('Enter Finishing City :'),
read(End),
findroute(Start,End),
writeList([List]).
findroute(Start,End):-
connected(Start,End).
findroute(Start,End):-
add(Start, List, [Start | List]),
connected(Start,Link), findroute(Link,End).
add(A,B,[A|B]).
writeList([]).
writeList([Head | Tail]):-
write(Head),
nl,
writeList(Tail).
Your findroute/2 predicate does not return the list, so the output can't work.
The call should look something like this:findroute(Start,End,List)
Obviously, the findroute/2 predicate must be changed to findroute/3:
findroute(Start,End,[Start,End]):-
connected(Start,End).
findroute(Start,End,List):-
connected(Start,Link),
add(Start,Rest,List),
findroute(Link,End,Rest).
(hint: be sure you understand why the add/3 call works even though Rest is uninstantiated at that point. Otherwise your tutor won't believe that this code is your homework! ;-) )
You may want to add a cut at the end of the first clause if you only want to find the shortest route.
Finally, List is already a list, so don't put square brackets around it when calling writeList/1!