I can put an import statement in a string, exec it, and it works (prints a random digit):
code = """ import random def f(): print random.randint(0,9) """ def f(): pass exec code f()
Now, if I put exec code
and f()
in their own function and call it, it doesn't work.
def test(): exec code f() test()
It says NameError: global name 'random' is not defined
.
The exec command is a powerful tool for manipulating file-descriptors (FD), creating output and error logging within scripts with a minimal change. In Linux, by default, file descriptor 0 is stdin (the standard input), 1 is stdout (the standard output), and 2 is stderr (the standard error).
Most of the time if you can do something in a function, you can do it in global scope or in a class definition or vice versa. There's an exception for from ... import * , which works at global scope but not inside a function.
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import.
Importing Modules To make use of the functions in a module, you'll need to import the module with an import statement. An import statement is made up of the import keyword along with the name of the module. In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.
How about this:
def test(): exec (code, globals()) f()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With