Getting inconsistent "invalid literal for int()" error - python-2.7

Although this is a super common error, I haven't found a solution for this particular issue.
I have a script with a line that reads
line = int(ser.readline())
Sometimes (not everytime!) when I run this script is get this error:
Traceback(most recent call last):
File "./project.py", line 28, in <module>
line = int(ser.readline())
ValueError: invalid literal for int() with base 10:' '
When this happens, I can simply restart the script, and it works fine.
What's going on here? Is there a way to prevent this from happening?
Here's the full script, for reference. The offending code is on line 28.
#!/usr/bin/python
import time
import serial
import subprocess
# -------------function for videos-------------
def play_vid_nonblocking(num):
return subprocess.Popen(["xterm", "-fullscreen", "-e", "omxplayer", "-o", "hdmi", "-r", "/home/pi/Ligia/{:02d}.mp4".format(num)])
# -------------sensor setup-------------
ser = serial.Serial('/dev/ttyACM0', 9600)
# -----------------------------------------
num_videos = 10
i = 1
p = None
time.sleep(60)
while True:
line = int(ser.readline())
print line
if line < 750:
if p is None or p.poll() is not None:
p = play_vid_nonblocking(i)
time.sleep(60)
i = i + 1
if i > num_videos:
i = 0
else:
pass
else:
pass
else:
pass
ser.close()

#jonrsharpe above suggested the script was sometimes reading whitespace. This was fixed by adding a "Try" statement:
try:
line = int(line)

Related

Get error line number Python

I am trying to debug python code, I want to pin point the line number in which error occurs. As per the posts found asked here the code gives the line no of the function being called. eg
if __name__ == '__main__':
try:
foo()
except:
<the code to print line no when error occurs>
But it gives me the line no of foo(),
Please help to find the exact line no in which error occurs.
Thanks,
You have to use the third return value of sys.exc_info() they call exc_tb in your example. Instead of using exc_tb.tb_lineno, you can browse the traceback object using traceback.extract_tb(exc_tb). The repr look like :
*** extract_tb:
[('<doctest...>', 10, '<module>', 'lumberjack()'),
('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
I suppose the line you are looking for is the last line of the structure. I haven't tested but this should do :
import sys, os, traceback
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
tb = traceback.extract_tb(exc_tb)[-1]
print(exc_type, tb[2], tb[1])

Python ConfigParser KeyError:

I am following an example to read a config file from the following: https://wiki.python.org/moin/ConfigParserExamples
But I get a KeyError and can't figure out why. It is reading the files and I can even print the sections. I think I am doing something really stupid. Any help greatly appreciated.
Here is the code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
import logging
config_default=ConfigParser.ConfigParser()
class Setting(object):
def get_setting(self, section, my_setting):
default_setting = self.default_section_map(section)[my_setting]
return default_setting
def default_section_map(self,section):
dict_default = {}
config_default.read('setting.cfg')
sec=config_default.sections()
options_default = config_default.options(section)
logging.info('options_default: {0}'.format(options_default))
for option in options_default:
try:
dict_default[option] = config_default.get(section, option)
if dict_default[option] == -1:
print("skip: %s" % option)
except:
print("exception on %s!" % option)
dict_default[option] = None
return dict_default
return complete_path
if __name__ == '__main__':
conf=Setting()
host=conf.get_setting('mainstuff','name')
#host=conf.setting
print 'host setting is :' + host
My config file is named setting.cfg and looks like this:
[mainstuff]
name = test1
domain = test2
[othersection]
database_ismaster = no
database_master = test3
database_default = test4
[mysql]
port = 311111
user = someuser
passwd = somecrazylongpassword
[api]
port = 1111
And the Error is this...
exception on domain! Traceback (most recent call last): File
"./t.py", line 51, in
host=conf.get_setting('mainstuff','name') File "./t.py", line 14, in get_setting
default_setting = self.default_section_map(section)[my_setting] KeyError: 'name'
Be sure that your complete file path is setting.cfg. If you put your file in another folder or if it is named different, Python is going to report the same KeyError.
you have no general section. in order to get the hostname you need something like
[general]
hostname = 'hostname.net'
in your setting.cfg. now your config file matches the program -- maybe you prefer to adapt your porgram to match the config file? ...this should get you started at least.
UPDATE:
as my answer is useless now, here is something you could try to build on (assuming it works for you...)
import ConfigParser
class Setting(object):
def __init__(self, cfg_path):
self.cfg = ConfigParser.ConfigParser()
self.cfg.read(cfg_path)
def get_setting(self, section, my_setting):
try:
ret = self.cfg.get(section, my_setting)
except ConfigParser.NoOptionError:
ret = None
return ret
if __name__ == '__main__':
conf=Setting('setting.cfg')
host = conf.get_setting('mainstuff', 'name')
print 'host setting is :', host
This error occurs mainly due to 2 reasons:
Issue in reading the config file due to not getting the proper path. Absolute path may be used. Try reading the config file first whether any issue.
f = open("config.ini", "r")
print(f.read())
Not been able to find mentioned section in config file.

Python subprocess cannot access the .bat file because it's used by another process

I coded a python script that creates a windows batch file which bates stamps PDF files.
The batch program runs just fine, if open/run it in Windows, e.g., by selecting it and hitting Enger.
But when I try to run subprocess on the batch file, I get the following error message:
Traceback (most recent call last):
File "C:\Apps\UtilitiesByMarc\bates_stamp_pdf_files_using_veryPDF_and_regex_match_groups_and_verbose_.py", line 56, in <module>
RetVal = subprocess.call(target_file_fullname, shell=False)
File "C:\Python27\lib\subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 896, in _execute_child
startupinfo)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
I can't figure out how to run subprocess in a way that would prevent the error message from occurring. Any suggestions would be much appreciated, especially references to an explanation of the problem.
Here's the python code:
# -*- coding: latin-1 -*-
# bates_stamp_pdf_files_using_veryPDF_.py
import os
import sys
import re
import time
import subprocess
exhibits_temp_dir = r'\\Hpquadnu\c\Svr1\K\data\Steinberg Nisan\Scans.Steinberg Nisan\Exhibits.Temp'
stamp_prg = r'"C:\Apps\pdfstamp_cmd_veryPDF\pdfstamp.exe"'
# DOES NOT WORK; VERBOSE MB DONE IN THE COMPILE STATEMENT srchptrn = (r"""([exEXapAPatAT]{2,3}_?) # Ex or Att or App, etc.
# ([0-9]+) # Seq. no of the document
# ([^0-9]+.+) # a non-digit character to separate the seq. no from other identifying chars.""", re.X)
srch_or_match_obj = re.compile(r"""([exEXapAPatAT]{2,3}_?) # Ex or Att or App, etc.
([0-9]+) # Seq. no of the document
([^0-9]+.+) # a non-digit character to separate the seq. no from other identifying chars.""", re.X)
target_file_fullname = exhibits_temp_dir + '\\' + 'bates_stamp.bat'
target_file_objname = open(target_file_fullname, 'w')
dirlist = os.listdir(exhibits_temp_dir)
for item in dirlist:
matches_obj = srch_or_match_obj.search(item)
if matches_obj:
item_no = str(matches_obj.group(2))
file_fullname = '"' + os.path.join(exhibits_temp_dir, item) + '"'
#Cmdline = stamp_prg -PDF "example.pdf" -o "marc_2013-06-12_AM_09-51-54_.pdf" -AT "Exhibit 1, page \p" -P5 -MLR-20 -FN301 -MTB-20
Cmdline = stamp_prg +' -PDF ' + file_fullname + ' -o ' + file_fullname + ' -AT "Exhibit ' + item_no + ', page \p" -P5 -MLR-20 -FN301 -MTB-20'
print Cmdline + '\r\n'
text2write = Cmdline + '\r\n'
target_file_objname.write(text2write)
target_file_objname.write('\n\n')
else:
print 'Not matched: ' + item
text2write = 'pause'
target_file_objname.write(text2write)
target_file_objname.close
time.sleep(1)
RetVal = subprocess.call(target_file_fullname, shell=False)
print 'Reval = ' + RetVal
print 'Job done'
Apparently you file is not closed when you run it. Maybe the parenthesis (bracket) :
target_file_objname.close()

EOF Error in Python 2

I am solving a problem on http://hackerrank.com using Python 2
The compiler is giving an error
Traceback (most recent call last):
File "/run-Lx3mHJ3G2jHRLRW9bjbX/solution.py", line 4, in
t = raw_input()
EOFError: EOF when reading a line
This is the code :
import sys
a = []
while 1:
t = raw_input()
if t=="":
break
else:
s = [i for i in t]
s.reverse()
a.append(s)
a.reverse()
for i in a:
for j in i:
sys.stdout.write(j)
sys.stdout.write('\n')
When I run it on my computer, it works fine.
Is it a problem I should report with the HackerRank interpreter or am I doing something wrong?
For sake of complete information, I already tried using "input()", "str(input())" and other possible variants.
HackerRank seems not to support the python idiom of repeating raw_input() until it gets an empty line. HackerRank apparently requires the submitted code to use the test description parameters in the header section (first line or two of input) to control the number of lines read.
Attempting to read past the last expected input line triggered a similar EOFError in my trials:
...
def main():
lines = []
line = raw_input()
while line:
lines.append(line)
line = raw_input() # line 232
...
resulted in
Status: EOFError thrown on line 232
Rewriting the input code to read just the expected number of lines was enough for the revised submission to pass. For example, for the 'Service Lane' warmup exercise in the Algorithms section:
...
first_line = raw_input()
freeway_length, testcase_count = parse_session_controls(first_line)
second_line = raw_input()
widths = parse_widths(second_line, freeway_length)
for _unused in range(testcase_count):
testcase_line = raw_input()
entrance_num, exit_num = parse_testcase(testcase_line, freeway_length)
print(measure_bottleneck(widths, entrance_num, exit_num))
...

What is the error in following python code

import sys
def Hello(name):
name = name + '!!!'
print 'Hello' , name
def main():
Hello(sys.argv[1])
if __name__ == '__main__':
main()
Here is the error
Traceback (most recent call last):
File "D:\pythonPractice\firstPython.py", line 13, in <module>
main()
File "D:\pythonPractice\firstPython.py", line 9, in main
Hello(sys.argv[1])
IndexError: list index out of range
I have also tried sys.argv[2] but error remains
First things first, I think the code you originally posted (with Hello(sys.argv[0])) is not what you actually have. It doesn't match the error, which states sys.argv[1], so what you probably have is:
def main():
Hello(sys.argv[1])
As to the error then, it's because you haven't provided an argument when running. You need to do so, such that sys.argv[1] exists:
python helloprog Pax
You would find a more robust main as:
def main():
if len(sys.argv) < 2:
Hello("whoever you are")
else:
Hello(sys.argv[1])
which will detect when you haven't provided an argument, and use a suitable default rather than raising an exception.
Have you used
sys.argv[0]
Since this returns a list , you may not have elements >1