0

How do I execute a string containing Python, without creating a new file, using excec() or using "os" module?

I've seen the similiar question, but the answeres always kind of created some "new file"(for example created something like this), or went out of the current code, but i want it to stay inside the code and execute it.

Example:

string_base64 = "eCA9ICJoZWxsbyBmZWxsb3ciCgoKcHJpbnQoeCkKeCA9ICJoZWxsbyBmZWxsb3ciCgoKcHJpbnQoeCkKeCA9ICJoZWxsbyBmZWxsb3ciCgoKcHJpbnQoeCkKeCA9ICJoZWxsbyBmZWxsb3ciCgoKcHJpbnQoeCk="

This b64 code has inside it strings and commands (+ For example imports) and it needs to run in the current file, without using exec() or modules

This Thread and the answers, didn't answer the question!

hoze
  • 11
  • 4
  • 1
    I think you'll have to provide an example of how to decode your sample string, and also why `exec()` doesn't work for you. `exec()` is the canonical way to do this; stating that you can't use makes this seem like an X/Y problem. – NicholasM Oct 07 '22 at 17:01
  • Does this need to run in some sort of limited environment where `exec` isn't available? If so, you may be out of luck. Some things are still possible with `eval` and things like `getattr`, but that's highly dependent on what your code needs to do. And no built-in solution is going to decrypt your code for you, you're still going to have to do that. Like NicholasM, I feel like we're missing something important here... or possibly you are. It's impossible to tell so far. – CrazyChucky Oct 19 '22 at 12:32
  • A straightforward [MRE] would certainly help. And please explain what about `exec` doesn't "stay inside the code and execute it" for your purposes. – CrazyChucky Oct 19 '22 at 12:48

1 Answers1

2

Buildin exec function seems to be doing exactly what you want: https://docs.python.org/3/library/functions.html#exec

yjay
  • 942
  • 4
  • 11