1

What I mean by the title is this for ex:

def write_to_file(*params):
    with open(path, 'r+', encoding="utf-8") as file:
        content = file.read()
        file.seek(0) 

        # custom code via func parameters to be executed
        # for example *params will be ["file.write("test" + '\n')", "]
        # and here will be like for loop that goes through the params ?
        # for code in params:
            #code.execute() ?
    
        file.truncate() 

Hopefully I explained it well, just wondering if you can do any of this.

// Edit (better explanation): I want to convert string into a code executable, "print(x)" -> print(x) that will be called in a function.

ZippoKs
  • 13
  • 3
  • 1
    You can pass a function into another function and then call it. Is that what you need? – khelwood Jan 13 '22 at 12:40
  • 1
    The reasonable way to do this is to have your function accept another function, i.e. a "callback" – juanpa.arrivillaga Jan 13 '22 at 12:41
  • 1
    for ex.: write_to_file(["x = 1", "print(x)", "x = len(content)", "print(x)"]) – ZippoKs Jan 13 '22 at 12:42
  • 1
    __Don't do this__ - https://stackoverflow.com/a/1832957/9296093 – matszwecja Jan 13 '22 at 12:45
  • 1
    Or to reverse it: only do this if you are in **full** control of the incoming strings, like: you typing them yourself. Otherwise, just assume your worst personal enemy sits in front of the computer and is allowed to type in those strings to be evaluated. – GhostCat Jan 13 '22 at 12:53
  • @GhostCat At this point you can just as well make it a selection of predetermined options and/or write them directly in the code. There are rare use-cases for eval, but this is __not__ one of them – matszwecja Jan 13 '22 at 12:58

2 Answers2

2

pass the function itself:

def write_to_file(func):
    with open(path, 'r+', encoding="utf-8") as file:
        content = file.read()
        file.seek(0) 
        func()
        file.truncate()

def func():
    print("foo")

write_to_file(func)
muliku
  • 416
  • 3
  • 17
  • I didn't explain it well, my bad. I want to convert string into a code executable, "print(x)" -> print(x) in a function. – ZippoKs Jan 13 '22 at 12:46
  • 1
    Evaluating arbitrary user-input code is a terrible idea – matszwecja Jan 13 '22 at 12:47
  • @ZippoKs in that case you van use 'eval': `eval("print(1)")` but that's not a good practice. If you need to use it, your code needs some reevaluation – muliku Jan 13 '22 at 12:49
  • Yes, eval was what I'm looking for, will do more research about it, thanks guys! – ZippoKs Jan 13 '22 at 12:50
-1

If you just need to execute code from a string (reading the contents of a file with .read() also returns them in form of a single or multiline string), then you might simply use eval() function for the purpose.

eval() is a built-in Python function that can evaluate any expression given in it, and any errors in expressions are also thrown on console accordingly. This function just evaluates the given single-line expression, and does not support assignment and other related operators. For other purposes, you may also want to use exec() Python function.

I initially wanted to comment it, but I lack 2 reputation score for it at the time of posting it, so have to post it as an answer here.

Harshit Gupta
  • 187
  • 1
  • 11