I have a file1.py:
def battery():
pass
// much more methods here
if __name__ == "__main__":
cmd = str((sys.argv)[1]) + "()"
os.system(cmd)
Now I want to call file1.battery() from the linux console with python file1.py battery.
But I get the error:
sh: 1: Syntax error: end of file unexpected
Advertisement
Answer
You can use eval for compiling string like code or use globals and locals:
def func():
return 'hello'
print eval('func()')
print globals()["func"]()
print locals()["func"]()
>>> hello
>>> hello
>>> hello
Also, the module can import itself:
import sys current_module = sys.modules[__name__] function = getattr(current_module, 'func') print function()