Print traceback to file when there is no exception - python

What specific Python 3 syntax must be changed below in order to successfully print a trackback form a successfully running function into a file that is located at aValidFileNameAndPath?
We need this to work in normal running functions where there is NO exception.
The Python 3 code we are using is:
import traceback
traceback.print_stack(file=aValidFileNameAndPath)
The error thrown by the above code is:
File "C:\path\to\script\in\our\app\ourScriptName.py", line 69, in ourFunctionName
traceback.print_stack(file=aValidFileNameAndPath)
File "C:\Program Files\Python39\lib\traceback.py", line 190, in print_stack
print_list(extract_stack(f, limit=limit), file=file)
File "C:\Program Files\Python39\lib\traceback.py", line 25, in print_list
print(item, file=file, end="")
AttributeError: 'str' object has no attribute 'write'
The other postings we have found on Stack Overflow have to do with printing exceptions. We do NOT want to print an exception. Instead, we just want to print out the chain of functions that called a specific function during normal functioning of the app when there is no exception to be thrown.

You are getting this error because where you are using the file path the code wants a file object.
To make a file object, use open, e.g. myfile = open(aValidFileNameAndPath)
You will also want to set the file to writing mode, e.g. open(path, 'w')
Then you can pass myfile as a paremeter, e.g. traceback.print_stack(file=myfile)
Then make sure to close the file with close
Here is a full example:
import traceback
myfile = open(aValidFileNameAndPath, 'w') # note that this will delete anything that alredy exists in the file
traceback.print_stack(file=myfile)
myfile.close()

Related

Import csv module file not opening

I am trying to open a csv file using the csv module and then trying to read some data off of it using this code.
import csv
def file_open():
input_file=str(input('enter the input file to use'))
while True:
try:
with open(input_file,'r') as grades:
grades_reader=csv.reader(grades, delimiter=',')
break
except FileNotFoundError:
print('FileNotFoundError')
input_file=str(input('enter the input file to use'))
row_num=1
for row in grades_reader:
print('row',row_num,row)
row_num+=1
file_open()
and the file opening seems to be working until it gets to the part where it has to read the data and then it gives me an i/o error saying the file is closed. I am quite new to python and would appreciate any insight on what I did wrong.
also input_file is meant to allow the user to pick any file but I will only be using it to call one file called Grades.csv if that information will help
EDIT: traceback error message.
Traceback (most recent call last):
File "C:\Users\musta\OneDrive\Documents\computer assignment programs\program 4\Program4.py", line 24, in <module>
file_open()
File "C:\Users\musta\OneDrive\Documents\computer assignment programs\program 4\Program4.py", line 18, in file_open
for row in grades_reader:
ValueError: I/O operation on closed file.
The file is closed because your break ends the loop, and the with body, therefore closing the file
You should keep that file reading code within the with indentation.
A csv.reader doesn't load the file into some in-memory list

I get the following error AttributeError: __enter__ when only using one with block

When I try to save the file lines in a list I with the following code I get the below error:
Traceback (most recent call last):
File "C:\Users\emiel\AppData\Roaming\Sublime Text 3\Packages\User\Making_a_list_from_file.py", line 7, in <module>
with filename as file_object:
AttributeError: __enter__
This is the code:
with filename as file_object:
lines=file_object.readlines()
for line in lines:
print(line.strip())
The error is telling you that the object you're using in the with statement is not of the right type. __enter__ is one of the methods called as part of the context manager protocol, and the type you're using doesn't have that method.
Based on your variable name, it looks like you may be using a file name where you want to be using a file object. The error message will then make sense, as strings are not context managers the way file objects are. Try changing your with statement to:
with open(filename) as file_object:

File not found with Python's fileinput

Given the following code:
# Edit build number in test report
print(path) # TODO remove
html_report = fileinput.input(path, inplace=True)
for line in html_report:
print(line.replace('$BUILD_NUMBER',
args.number).rstrip())
html_report.close()
I get the following output:
/home/jenkins/workspace/reports/report201610261053.html
Traceback (most recent call last):
File "report_generator.py", line 58, in <module>
for line in html_report:
File "/usr/lib/python2.7/fileinput.py", line 252, in next
line = self.readline()
File "/usr/lib/python2.7/fileinput.py", line 321, in readline
os.rename(self._filename, self._backupfilename)
OSError: [Errno 2] No such file or directory
If I just use the command:
gedit /home/jenkins/workspace/reports/report201610261053.html
I can check that the file exists. In fact, if it didn't I would expect this error to be raised in the fileinput.input() line, not in the line loop.
Any idea of what's wrong?
What is your "path" value?
I think you should try to use absolute path
You can also check the user permissions to file.
I don't see anything wrong in the code that you have shown.
I can check that the file exists. In fact, if it didn't I would expect
this error to be raised in the fileinput.input() line, not in the line
loop.
The error is reported only when an attempt is made to open file and it happens in the for loop.
Is it possible that your code is running under a different user and doesn't see the file on that path as compared to you manually verifying file existence?

Using py_compile.compile() from within a Python script

I am trying to understand the docs.
My Python script generates Python code that runs much later, so I want to check now if what I generated is valid.
The docs say py_compile.compile(file[, cfile[, dfile[, doraise]]]) and
If doraise is true, a PyCompileError is raised when an error is encountered while compiling file
So, I tried
source = open(generatedScriptPath, 'rt').read() + '\n'
try:
import py_compile
x = py_compile.compile(source, '', '', True)
except py_compile.PyCompileError, e:
print str(e)
but the inner Exception is never hit, instead an outer Exception is being caught:
Traceback (most recent call last): File
"H:/code/testgen/testGen.py", line 293, in <module>
x = py_compile.compile(source, '', '', True) File "C:\Python27\lib\py_compile.py", line 106, in compile
with open(file, 'U') as f: IOError: [Errno 2] No such file or directory: '# This script was auto-generated ...
How can I fix this? Note that I am open to alternatives, I just want to ask the simplest way. "Is the code I just generated syntactically valid Python?"
Read the error message: "No such file or directory". The first argument is supposed to be a file name to open. Or read the docs: "The source code is loaded from the file name /file/." You might prefer the "compile" builtin, which can compile a string of Python.

Python 3.4.1: Can't Open and Read a local file

def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
data = Source_obj.read()
I am having trouble opening this file while located in a sub-directory directly underneath my Python file... is there a better way to open files from ANY directory on my computer?
FileNotFoundError: [Errno 2] No such file or directory: 'WebSource\\EXAMPLE SOURCE.htm'
I can't read from the file because I get the following error:
C:\python34\python.exe G:\Robot\test.py
Process started >>>
Traceback (most recent call last):
File "G:\Robot\test.py", line 118, in <module>
functION()
File "G:\Robot\test.py", line 64, in functION
data = Source_obj.read()
AttributeError: 'str' object has no attribute 'read'
<<< Process finished. (Exit code 1)
================ READY ================
BTW: The file to be read is just a source file from an HTML Chrome webpage.
EDIT
I'm looking for more help with the path and wondering why I get the first mentioned Traceback regarding the path
os.path.relpath() returns a string, not an open file object. You'll need to open a file first; use the open() function:
def functION():
Source_obj = path.relpath(r"WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as fileobj:
data = fileobj.read()
with here treats the file object as a context manager; when the indented codeblock under the statement is exited (either because the code completed or an exception occurred), the file object will automatically be closed.
Your Source_obj is just a string, not a file.
def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as f:
data = f.read()
By open()-ing it you can read from the file. Using the with context manager, the file will be properly closed for you when you leave that block of code.

Categories

Resources