kame
kame

Reputation: 21960

Call a function from the console as an argument

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

Upvotes: 1

Views: 47

Answers (1)

JRazor
JRazor

Reputation: 2817

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()

Upvotes: 1

Related Questions