Regexpr in python - python

for printJobString in logfile:
userRegex = re.search('(\suser:\s)(.+?)(\sprinter:\s)', printJobString)
if userRegex:
userString = userRegex.group(2)
pagesInt = int(re.search('(\spages:\s)(.+?)(\scode:\s)', printJobString).group(2))
above is my code, when I run this program in the module I end up getting,
Traceback (most recent call last):
File "C:\Users\brandon\Desktop\project3\project3\pages.py", line 45, in <module>
log2hist("log") # version 2.
File "C:\Users\brandon\Desktop\project3\project3\pages.py", line 29, in log2hist
pagesInt = int(re.search('(\spages:\s)(.+?)(\scode:\s)', printJobString).group(2))
AttributeError: 'NoneType' object has no attribute 'group'
I know this error means the search is returning None but I'm not sure how to handle this case. Any help would be appreciated, very new to python and still learning the basics.
I am writing a program that should print out the number of pages a user has.
180.186.109.129 code: k n h user: luis printer: core 2 pages: 32
is a target string, my python file is trying to create a data file that has one line for each user and contains the total number of pages printed

The reason it happens is because your regexp does not find anything and returns None
re.search('(\spages:\s)(.+?)(\scode:\s)') returns None
use an if statement to test if it's not None before you try to group
for printJobString in logfile:
userRegex = re.search('(\suser:\s)(.+?)(\sprinter:\s)', printJobString)
if userRegex:
userString = userRegex.group(2)
pagesInt = re.search('(\spages:\s)(.+?)(\scode:\s)', printJobString)
if pagesInt:
pagesInt = int(pageInts.group(2))

Related

TypeError: expected string or bytes-like object and works on server but not on PC

Introduction
I have problem with python program written in python 3.4.2. At the beginning i want to say, that it's not my program.
When i connect with server by SSH and compile it, it works just fine.
Server and PC specification
:
...and from my PC:
I have different Python version, but i can't compile it at 3.4.2, because there is no typing module for this specific version, which i need. I don't know if GCC version could cause this problem, but i've tried different versions.
I've downloaded it, and tried to compile it by myself. I run it in the exactly same way.
The real problem
Traceback (most recent call last):
File "gads.py", line 28, in <module>
lists = list_working.ListWorking(files_data)
File "/home/grzesiek/googleads/lib/list_working.py", line 43, in __init__
self._acc = self._split_str_list(list_data['accepted']['content'])
File "/home/grzesiek/googleads/lib/common.py", line 69, in _split_str_list
splited = re.split(separator, content)
File "/usr/local/lib/python3.5/re.py", line 203, in split
return _compile(pattern, flags).split(string, maxsplit)
TypeError: expected string or bytes-like object
So far i know that ListWorking(files_data) passes some files which are dictionaries, and at the end when i want to use regex it throws an error. But i can't change these dictionaries to strings or lists, because then it compiles, but erase data that i provide to ListWorking()
Here is fragment of code which i've tried to change:
def __init__(self, list_data: dict) -> None:
self._acc = self._split_str_list(list_data['accepted']['content'])
self._acc = self._del_dup(self._acc)
self._ign = self._split_str_list(list_data['ignored']['content'])
self._ign = self._del_dup(self._ign)
self._pro = self._split_str_list(list_data['protected']['content'])
self._pro = self._del_dup(self._pro)
self._fign = self._split_str_list(list_data['full_ignored']['content'])
self._fign = self._del_dup(self._fign)
self._key = self._split_str_list(list_data['keywords']['content'])
self._key = self._del_dup(self._key)
self._unk = self._split_str_list(list_data['unknown']['content'])
self._unk = self._del_dup(self._unk)
self._sw = self._split_str_list(list_data['stopwords']['content'])
And where the last error occurs:
def _split_str_list(content: str, separator: str = '\n') -> list:
"""Split string to list"""
splited = re.split(separator, content)
splited = list(x.strip() for x in splited)
splited = list(filter(None, splited))
return splited
Also, in Python 3.4.2 it comes to import typing and throws an error, because there is no typing lib in this version of Python.
So - how is it possible to work fine on Linux server but it doesn't on my PC?
Well, the answer was much simpler than i thought it would be...
I just had to install correct version of enca, code author didn't wrote the specific informations if something is missing, so it was very hard to find, because whole project has about ~5000 lines of code, and enca was used only by one function.
It had nothing to do with Linux or GCC.

Feedparser Python Error : KeyError : 'title'

I have seen a lot of KeyCount Errors online but none of them quite match the troubles that I'm having. I am using feed parser to try and create a one run application that accesses all the URLs in a text file and outputs all the entries in each URL. When I run this code :
import feedparser as f
with open('addresses.rtf', 'r') as addresses:
for line in addresses:
d = f.parse(line)
print d["feed"]["title"]
print ""
print d.feed.subtitle
print ""
for post in d.entries:
print post.title
print post.link
print ""
I get this error message :
Traceback (most recent call last):
File "/Users/Josh/Desktop/Feed Parser Python Project/init.py", line 7, in <module>
print d["feed"]["title"]
File "build/bdist.macosx-10.6-intel/egg/feedparser.py", line 375, in __getitem__
return dict.__getitem__(self, key)
KeyError: 'title'
My text file is just a .rtf file that has a URL on each line (3 lines).
If someone could give us a hand please let me know and if you need any extra info please don't hesitate to ask. Any help is welcome. Thank you!
It's hard to tell exactly what is wrong here, but in the general case, any KeyError is because the data you are trying to access is not exactly what you expected. It's best to throw your assumptions out the window and take a close look at the actual data that your code is working with.
For debugging, I would recommend taking a close look at what happens before the error. What is the value of line as you read the file? Is it correct? What is the value of d? Did the call to f.parse(line) result in a valid object?

TypeError: in Python

I have an issue, where a function returns a number. When I then try to assemble a URL that includes that number I am met with failure.
Specifically the error I get is
TypeError: cannot concatenate 'str' and 'NoneType' objects
Not sure where to go from here.
Here is the relevant piece of code:
# Get the raw ID number of the current configuration
configurationID = generate_configurationID()
# Update config name at in Cloud
updateConfigLog = open(logBase+'change_config_name_log.xml', 'w')
# Redirect stdout to file
sys.stdout = updateConfigLog
rest.rest(('put', baseURL+'configurations/'+configurationID+'?name=this_is_a_test_', user, token))
sys.stdout = sys.__stdout__
It works perfectly if I manually type the following into rest.rest()
rest.rest(('put', http://myurl.com/configurations/123456?name=this_is_a_test_, myusername, mypassword))
I have tried str(configurationID) and it spits back a number, but I no longer get the rest of the URL...
Ideas? Help?
OK... In an attempt to show my baseURL and my configurationID here is what I did.
print 'baseURL: '+baseURL
print 'configurationID: '+configurationID
and here is what I got back
it-tone:trunk USER$ ./skynet.py fresh
baseURL: https://myurl.com/
369596
Traceback (most recent call last):
File "./skynet.py", line 173, in <module>
main()
File "./skynet.py", line 30, in main
fresh()
File "./skynet.py", line 162, in fresh
updateConfiguration()
File "./skynet.py", line 78, in updateConfiguration
print 'configurationID: '+configurationID
TypeError: cannot concatenate 'str' and 'NoneType' objects
it-tone:trunk USER$
What is interesting to me is that the 369596 is the config ID, but like before it seems to clobber everything called up around it.
As kindall pointed out below, my generate_configurationID was not returning the value, but rather it was printing it.
# from generate_configurationID
def generate_configurationID():
dom = parse(logBase+'provision_template_log.xml')
name = dom.getElementsByTagName('id')
p = name[0].firstChild.nodeValue
print p
return p
Your configurationID is None. This likely means that generate_configurationID() is not returning a value. There is no way in Python for a variable name to "lose" its value. The only way, in the code you posted, for configurationID to be None is for generate_configurationID() to return None which is what will happen if you don't explicitly return any value.
"But it prints the configurationID right on the screen!" you may object. Sure, but that's probably in generate_configurationID() where you are printing it to make sure it's right but forgetting to return it.
You may prove me wrong by posting generate_configurationID() in its entirety, and I will admit that your program is magic.

Python: TypeError: 'float' object is not callable

I am trying to join 2 strings using this code:
def __get_temp(self):
return float(self.ask('RS'))
def __set_temp(self, temp):
set = ('SS' + repr(temp))
stat = self.ask(set)
return self.check(stat)
temp = property(__get_temp, __set_temp)
Once together, I then send a signal over a serial bus using PyVisa. However, when I try to call the function, I get
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
chil.temp(13)
TypeError: 'float' object is not callable
I've tried looking around for explanation of this error, but none of them make any sense. Anyone know what is going on?
It looks like you are trying to set the property temp, but what you're actually doing is getting the property and then trying to call it as function with the parameter 13. The syntax for setting is:
chil.temp = 13

AttributeError: xmlNode instance has no attribute 'isCountNode'

I'm using libxml2 in a Python app I'm writing, and am trying to run some test code to parse an XML file. The program downloads an XML file from the internet and parses it. However, I have run into a problem.
With the following code:
xmldoc = libxml2.parseDoc(gfile_content)
droot = xmldoc.children # Get document root
dchild = droot.children # Get child nodes
while dchild is not None:
if dchild.type == "element":
print "\tAn element with ", dchild.isCountNode(), "child(ren)"
print "\tAnd content", repr(dchild.content)
dchild = dchild.next
xmldoc.freeDoc();
...which is based on the code example found on this article on XML.com, I receive the following error when I attempt to run this code on Python 2.4.3 (CentOS 5.2 package).
Traceback (most recent call last):
File "./xml.py", line 25, in ?
print "\tAn element with ", dchild.isCountNode(), "child(ren)"
AttributeError: xmlNode instance has no attribute 'isCountNode'
I'm rather stuck here.
Edit: I should note here I also tried IsCountNode() and it still threw an error.
isCountNode should read "lsCountNode" (a lower-case "L")

Categories