[Python] Syntax error with exec call in Python

Discussão em 'Python' iniciado por Stack, Março 19, 2025.

  1. Stack

    Stack Membro Participativo

    Quick python question about the exec command. I'm have Python 2.7.6 and am trying to make use of the exec to run some code stored in a .txt file. I've run into a syntax error and am not entirely sure what is causing it.

    Traceback (most recent call last):
    File "/Users/XYZ/Desktop/parser.py", line 46, in <module>
    try_code(block)
    File "<string>", line 1
    x = 'Hello World!'
    ^
    SyntaxError: invalid syntax


    I initially thought it was complaining about carriage returns, but when I tried to edit them .replace them with ' ' I still received this error message. I've tried variations to see what appears to be the issue and it always declares the error as the first ' or " the program encounters when it runs exec.

    Here is the try_code(block) method

    def try_code(block):
    exec block


    And the main body of the program

    inputFile = open('/Users/XYZ/Desktop/test.txt', 'r+')

    starter = False
    finished = False
    check = 1
    block = ""

    for val in inputFile:
    starter = lookForStart(val)
    finished = lookForEnd(val)

    if lookForStart:
    check = 1
    elif finished:
    try_code(block)

    if check == 1:
    check = 0
    elif finished == False:
    block = block + val


    Basically I'm trying to import a file (test.txt) and then look for some embedded code in it. To make it easier I surrounded it with indicators, thus starter and finished. Then I concatenate all the hidden code into one string and call try_code on it. Then try_code attempts to execute it (it does make it there, check with print statements) and fails with the Syntax error.

    As a note it works fine if I have hidden something like...

    x = 5
    print x


    so whatever the problem is appears to be dealing with strings for some reason.

    EDIT


    It would appear that textedit includes some extra characters that aren't displayed normally. I rewrote the test file in a different text editor (text wrangler) and it would seem that the characters have disappeared. Thank you all very much for helping me solve my problem, I appreciate it.

    Continue reading...

Compartilhe esta Página