0

The exec() function is not executing a string correctly.

def servlistappend(x):
    file = open("blarg.txt",'r')
    read = str(file.read())
    print(read)
    tbe = "list = "+read
    print(tbe)
    exec(tbe)
    print(list)
    list.append(x)
    print(list)
    file.close()
    file = open("blarg.txt",'w')
    file.write(str(list))
    file.close()
def servlistremove(x):
    file = open("blarg.txt",'r')
    read = str(file.read())
    print(read)
    tbe = "list = "+read
    print(tbe)
    exec(tbe)
    print(list)
    if x in list:
        list.remove(x)
    else:
        print("that element does not exist")
    print(list)
    file.close()
    file = open("blarg.txt",'w')
    file.write(str(list))
    file.close()
servlistremove(2345)

The contents of blarg.txt are: [1234,2345,2345,2345]

When run, print(read) correctly outputs the string [1234,2345,2345,2345] and print(tbe) correctly outputs the stringlist = [1234, 2345, 2345, 2345]. After that, exec(tbe) and print(list) outputs <class 'list'> while it is instead supposed to output the list [1234,2345,2345,2345]. Does anyone know why this happens?

1 Answer 1

0

You have to assign a variable to the exec call. So list = exec(tbe)

Also, it is generally a bad practice to use exec or eval. I'd recommend that you use either json.load or ast.literal_eval if you want to convert a string to a python object.

The reason for the <class 'list'> printout is that list is a python builtin and you just printed out what that builtin object is.

Edit: I forgot exec wouldn't return the list, you have to use eval

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.