porting Python 2 program to Python 3, random line generator

2024/9/30 11:40:30

I have a random line generator program written in Python2, but I need to port it to Python3. You give the program the option -n [number] and a file argument to tell it to randomly output [number] number of lines from the file. Here is the source for the program:

#!/usr/bin/pythonimport random, sys
from optparse import OptionParserclass randline:def __init__(self, filename):f = open(filename, 'r')self.lines = f.readlines()f.close()def chooseline(self):return random.choice(self.lines)def main():version_msg = "%prog 2.0"usage_msg = """%prog [OPTION]... [FILE] [FILE]...Output randomly selected lines from each FILE."""parser = OptionParser(version=version_msg,usage=usage_msg)parser.add_option("-n", "--numlines",action="store", dest="numlines", default=1,help="output NUMLINES lines (default 1)")options, args = parser.parse_args(sys.argv[1:])try:numlines = int(options.numlines)except:parser.error("invalid NUMLINES: {0}".format(options.numlines))if numlines < 0:parser.error("negative count: {0}".format(numlines))if len(args) < 1:parser.error("input at least one operand!")for index in range(len(args)):input_file = args[index]try:generator = randline(input_file)for index in range(numlines):sys.stdout.write(generator.chooseline())except IOError as (errno, strerror):parser.error("I/O error({0}): {1}".format(errno, strerror))if __name__ == "__main__":main()


When I run this with python3:

python3 randline.py -n 1 file.txt

I get the following error:

  File "randline.py", line 66except IOError as (errno, strerror):^
SyntaxError: invalid syntax

Can you tell me what this error means and how to fix it?

Thanks!

Answer

The line "except IOError as (errno, strerror)" relies on a the little used obscure fact that exceptions in Python 2 are iterable, and that you can iterate over the parameters given to the exception by iterating over the exception itself.

This of course breaks the "Explicit is better than implicit" rule of Python and has as such been removed in Python 3, so you can no longer do that. Instead do:

except IOError as e:errno, strerror = e.args

This is clearer and works under all versions of Python.

https://en.xdnf.cn/q/71092.html

Related Q&A

Symbol not found, Expected in: flat namespace

I have a huge gl.pxd file with all the definitions of gl.h, glu.h and glut.h. For example it has these lines:cdef extern from <OpenGL/gl.h>:ctypedef unsigned int GLenumcdef void glBegin( GLenum m…

Why does Django not generate CSRF or Session Cookies behind a Varnish Proxy?

Running Django 1.2.5 on a Linux server with Apache2 and for some reason Django seems like it cannot store CSRF or Session cookies. Therefore when I try to login to the Django admin it gives me a CSRF v…

Shared state with aiohttp web server

My aiohttp webserver uses a global variable that changes over time:from aiohttp import web shared_item = blaasync def handle(request):if items[test] == val:shared_item = doedaprint(shared_item)app =…

ModuleNotFoundError: No module named matplotlib.pyplot

When making a plot, I used both Jupyter Notebook and Pycharm with the same set of code and packages. The code is: import pandas as pd import numpy as np import matplotlib.pyplot as plt # as in Pycha…

python linux - display image with filename as viewer window title

when I display an image with PIL Image it opens an imagemagick window but the title is some gibberish name like tmpWbfj48Bfjf. How do I make the image filename to be the title of the viewer window?

Request body serialization differences when lambda function invoked via API Gateway v Lambda Console

I have a simple API set up in AWS API Gateway. It is set to invoke a Python 2.7 lambda function via API Gateway Proxy integration.I hit a strange error in that the lambda worked (processed the body co…

Determining a homogeneous affine transformation matrix from six points in 3D using Python

I am given the locations of three points:p1 = [1.0, 1.0, 1.0] p2 = [1.0, 2.0, 1.0] p3 = [1.0, 1.0, 2.0]and their transformed counterparts:p1_prime = [2.414213562373094, 5.732050807568877, 0.7320508075…

Split datetime64 column into a date and time column in pandas dataframe

If I have a dataframe with the first column being a datetime64 column. How do I split this column into 2 new columns, a date column and a time column. Here is my data and code so far:DateTime,Actual,Co…

Django - Setting date as date input value

Im trying to set a date as the value of a date input in a form. But, as your may have guessed, its not working.Heres what I have in my template:<div class="form-group"><label for=&qu…

ReduceLROnPlateau gives error with ADAM optimizer

Is it because adam optimizer changes the learning rate by itself. I get an error saying Attempting to use uninitialized value Adam_1/lr I guess there is no point in using ReduceLRonPlateau as Adam wil…