Porting a Python 2 program to Python 3, a random line generator

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

#!/usr/bin/python import random, sys from optparse import OptionParser class 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 66 except IOError as (errno, strerror): ^ SyntaxError: invalid syntax 

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

Thanks!

+6
source share
3 answers

This line is the wrong syntax:

 except IOError as (errno, strerror): 

The correct form:

 except IOError as err: 

then you can learn err for attributes like errno , etc.

I'm not sure where you got the source string, this is also the wrong Python 2.x syntax.

+6
source

The string "except IOError as (errno, strerror)" based on the unused little obscure fact that exceptions in Python 2 are iterable and that you can iterate over the parameters specified for the exception by iterating over the exception itself.

This, of course, violates the Explicit Better Than Implicit rule of Python and as such is removed in Python 3, so you can no longer do this. Instead, run:

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

This is clearer and works under all versions of Python.

+9
source

To convert your program from python 2 to python 3, use the 2to3 tool.

http://docs.python.org/library/2to3.html

-1
source

Source: https://habr.com/ru/post/899346/


All Articles