IndexError when trying to execute a Script - python

I'm trying to figure out why this
def scanner(fileName, function):
with open(fileName) as file:
for line in file:
function(line)
def toSmallLetters(line):
print line.lower()
def paramin(fileName):
scanner(fileName, toSmallLetters)
if __name__ == "__main__":
import sys
paramin(sys.argv[1])
throws this error:
Traceback (most recent call last):
File "script.py", line 14, in <module>
paramin(sys.argv[1])
IndexError: list index out of range
What's wrong?

You are getting:
Traceback (most recent call last):
File "script.py", line 14, in <module>
paramin(sys.argv[1])
IndexError: list index out of range
because when you run the script you need to supply a parameter, presumably the file name that you want to scan. If the file is called script.py you might run as:
python script.py name-of-file-to-scan

sys module provides access to any command-line arguments via the sys.argv.
Provide argument while running program.
ex:
python script.py file_name

Related

get python Traceback in the powershell error handling

I've a python call from a powershell terminal.
minimalistic example:
Try {
& python "test.py"
}
Catch {
# Place individual error handling here
$ErrorMessage = "$($_.Exception.Message)"
}
echo $ErrorMessage
test.py raises an error, example content can be:
def make_sum():
return a+b
if __name__ == "__main__":
make_sum()
Why does the $ErrorMessage variable contain only the first line of python traceback?
Traceback (most recent call last):
I'd need complete call stack info as python provides:
Traceback (most recent call last):
File "d:/.../test.py", line 10, in <module>
make_sum()
File "d:/.../test.py", line 7, in make_sum
return a+b
NameError: name 'a' is not defined
Any advice how to get a complete traceback into the string variable in powershell?
Thank you,
Honza

Python tracebacks, how to hide absolute paths?

I would like to know if there is an easy way to prevent Python tracebacks to print the full path of files when there is an error. For example, the traceback below prints the absolute path of the file generating the exception:
Traceback (most recent call last):
File "C:/Users/user/Documents/project/project_align/src/main.py", line 62, in <module>
raise Exception
Exception
I wish it to just print the relative path instead: project_align/src/main.py
Is there a configuration parameter somewhere to force this?
I do not know if there is a flag to do this, but if you really want to, you can override sys.excepthook with your own function, within which you can create a TracebackException, remove all filenames from the frame summaries, and format and print it.
import os
import sys
import traceback
def handler(_exception_type, _value, t):
exc = traceback.TracebackException(_exception_type, _value, t)
# replace file names for each frame summary
for frame_summary in exc.stack:
frame_summary.filename = os.path.relpath(frame_summary.filename)
# format and print the exception
print(''.join(exc.format()), file=sys.stderr)
sys.excepthook = handler
def crashes_hard():
print(1 / 0)
def crashes():
crashes_hard()
crashes()
The output is
Traceback (most recent call last):
File "scratch_1.py", line 31, in <module>
crashes()
File "scratch_1.py", line 28, in crashes
crashes_hard()
File "scratch_1.py", line 24, in crashes_hard
print(1 / 0)
ZeroDivisionError: division by zero
The original output is
Traceback (most recent call last):
File "/home/abhijat/.config/.../scratches/scratch_1.py", line 31, in <module>
crashes()
File "/home/abhijat/.config/.../scratches/scratch_1.py", line 28, in crashes
crashes_hard()
File "/home/abhijat/.config/.../scratches/scratch_1.py", line 24, in crashes_hard
print(1 / 0)
ZeroDivisionError: division by zero

How can I run many python scripts at once?

I'm working on some python scripts using PyCharm. Running scripts from PyCharm works fine, but I tried bundling them up with a batch file and cmd just goes nuts:
C:\Users\White Python\Desktop\Fran\theconfluence\graphs\leaderboard>python htmlcreator.py
Traceback (most recent call last):
File "htmlcreator.py", line 4, in <module>
w = open(str(Path(__file__).parents[2]) + "/week.txt", "r")
File "C:\Users\White Python\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 617, in __getitem__
raise IndexError(idx)
IndexError: 2
C:\Users\White Python\Desktop\Fran\theconfluence\graphs\leaderboard>cd ..\retention
C:\Users\White Python\Desktop\Fran\theconfluence\graphs\retention>python creategraph.py
['C:\\Users\\White Python\\Desktop\\Fran\\theconfluence\\graphs\\retention', 'C:\\Users\\White Python\\AppData\\Local\\Programs\\Python
\\Python38-32\\python38.zip', 'C:\\Users\\White Python\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\White Python\
\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\White Python\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Us
ers\\White Python\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages']
Traceback (most recent call last):
File "creategraph.py", line 9, in <module>
w = open(str(Path(__file__).parents[2]) + "/week.txt", "r")
File "C:\Users\White Python\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 617, in __getitem__
raise IndexError(idx)
IndexError: 2
Other scripts which did not require importing modules worked fine. Help!
Is your html creator a script? Or more like module? If it's like a module the try:
python -m htmlcreator

image_url = sys.argv[1] IndexError: list index out of range

I am having an issue with the following section of Python code:
import sys
import requests
import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
image_url = sys.argv[1]
cred = credentials.Certificate('certificate.json')
firebase_admin.initialize_app(cred,{'storageBucket':'gs://rpi-demo-6d21d.appspot.com'})
bucket = storage.bucket()
image_data = requests.get(image_url).content
blob = bucket.blob('happy.jpg')
blob.upload_from_string(image_data,content_type='image/jpg')
print(blob.public_url)
Specifically the error is as follows:
Traceback (most recent call last):
File "demo4.py", line 6, in <module>
image_url = sys.argv[1]
IndexError: list index out of range
sys.argv list is populated from the command line arguments passed to the script, so in case none are provided it's expected to get an error like
Traceback (most recent call last):
File "demo4.py", line 6, in <module>
image_url = sys.argv[1]
IndexError: list index out of range
An easy repro is to put
import sys
print(sys.argv[1])
in demo.py and run it using python demo.py. You'll get the output
$ python demo.py
Traceback (most recent call last):
File "demo.py", line 2, in <module>
print(sys.argv[1])
IndexError: list index out of range
but if you pass an argument to it using python demo.py foo you'll get the desired output:
$ python demo.py foo
foo
Specifically for your example, looks like when calling demo4.py script you're not passing image url command line argument. You can pass it using python demo4.py <image_url_goes_here>.

Why does the Python linecache affect the traceback module but not regular tracebacks?

Consider the following Python program:
code = """
def test():
1/0
"""
filename = "<test>"
c = compile(code, filename, 'exec')
exec(c)
import linecache
linecache.cache[filename] = (len(code), None, code.splitlines(keepends=True), filename)
import traceback
print("Traceback from the traceback module:")
print()
try:
test()
except:
traceback.print_exc()
print()
print("Regular traceback:")
print()
test()
I am dynamically defining a function that raises an exception and adding it to the linecache. The output of the code is
Traceback from the traceback module:
Traceback (most recent call last):
File "test.py", line 20, in <module>
test()
File "<test>", line 3, in test
1/0
ZeroDivisionError: division by zero
Regular traceback:
Traceback (most recent call last):
File "test.py", line 28, in <module>
test()
File "<test>", line 3, in test
ZeroDivisionError: division by zero
If I then get a traceback from that function using the traceback module, the line of code from the function is shown (the 1/0 part of the first traceback). But if I just let the code raise an exception and get the regular traceback from the interpreter, it doesn't show the code.
Why doesn't the regular interpreter traceback use the linecache? Is there a way to make the code appear in regular tracebacks?
The default sys.excepthook uses a separate, C-level implementation of traceback printing, not the traceback module. (Perhaps this is so it still works even if the system is too borked to use traceback.py.) The C implementation doesn't try to use linecache. You can see the code it uses to retrieve source lines in _Py_DisplaySourceLine.
If you want tracebacks to use the traceback module's implementation, you could replace sys.excepthook with traceback.print_exception:
import sys
import traceback
sys.excepthook = traceback.print_exception

Categories

Resources