-1

The text file contains Python codes.
My task is to write a program which checks if it could run in python. I cannot find out how to check if the lines are correct in python. I can read lines from the text file, but still don't know how to decide if the current line would run without any error messages. If it would run the program prints True, else False.

lst=[]
with open("be.txt","r") as be:
    for line in be:
        lst.append(line.strip("\n"))

For example: A line is: "for i in range(8:"
The result should be False, because this ")" is missing.

tgtg
  • 1
  • 1
  • 2
    Why don't you change the extension from `txt` to `py` and run it? – Juan C May 08 '19 at 20:54
  • I would do, but the exercise highlights, that the program I write has to check if it could run or not. I clarified the question too in case. – tgtg May 08 '19 at 21:03
  • Welcome to StackOverflow. You should make two improvements to your question to get higher quality answers: 1) when you say "a code", that either means some encrypted text or a set of standards. In modern parlance however, "code" (notice no 'a') means programming statements. So "I have a text file that contains Python code." makes a lot more sense. 2) Your code example is very hard to read. Try indenting it with four spaces and adding line breaks. – Heath Raftery May 08 '19 at 21:30
  • Will keep that in mind. I hope it is way more better now. – tgtg May 08 '19 at 22:04

3 Answers3

0

Use exec and catch exceptions. exec will attempt to execute the line as Python code. If it succeeds then the line is executed and any side-effects (eg. the creation of new variables) take place. If not, an exception is thrown and you can skip it and move on to the next line. Something like this:

lst=[]
with open("be.txt","r") as be:
    for line in be:
        try:
            exec(line)
            lst.append(line.strip("\n"))
        except:
            pass

Note this will not work if a single line is not a complete Python statement. Eg. if you have a function def or a for loop over several lines, you'll have to exec them all at once to succeed.

Heath Raftery
  • 3,643
  • 17
  • 34
0

You can use exec:

with open("be.txt","r") as be:
    source = be.read()

try:
    exec(source)
    print("True")
except Exception as e:
    print(e) #this add some info on where the error occurred
    print("False")

First create a single string source holding all the code in your file.
Then in a try except block use exec to se if it runs. If it fails anywhere, an exception will be raised, and the except block is executed.

Generally functions like exec or eval are considered dangerous and nasty (see for example here or here) but I think in your case is the simplest thing you can do.

Valentino
  • 7,291
  • 6
  • 18
  • 34
0

The only way to know whether the code would run in python without any error messages is to execute it. The following would do that. Of course, you would need to go to extra lengths to suppress any output if the program is correct and produces output.

def runner():
    with open("be.txt","r") as f:
        code = f.read()
    try:
        exec(code)
    except Exception as e:
        print("False")
    else:
        print("True")

runner()
Booboo
  • 38,656
  • 3
  • 37
  • 60