I have a noob question.
I got a python script path1/path2/file.py
The script has a function:
def run (datetime = None):
In the shell I call
import path1.path2.file
import datetime
path1.path2.file.run(datetime = datetime(2011,12,1))
but I am getting TypeError: 'module' object is not callable
whats the correct way to call the method in the shell?
5 Answers 5
The problem is actually in the datetime module. You are trying to call the module itself. The function you want to call is itself called datetime. so what you want to call is:
datetime.datetime()
OR you can import the function with:
from datetime import datetime
and then call it with:
datetime()
Comments
You can write:
import path1
path1.path2.file.run(...)
Or:
from path1.path2.file import run
run(...)
Don't forget that you need an __init__.py file in each directory (path1 and path2) to make the directory as a module (and then, allow it to be importable.). That file can just be empty if you have nothing to put in it.
2 Comments
__init__.py file in the path1 directory AND path2 directory ?Try the following:
from path1.path2.file import run
Comments
If none of these work, here is a (a little bit dirty) way of doing it:
# Python <= 2.7
namespace = {}
exec open("path1/path2/file.py").read() in namespace
namespace["run"](datetime=datetime.datetime(2011,12,1))
or
# Python >= 3.0
namespace = {}
exec(open("path1/path2/file.py").read(), namespace)
namespace["run"](datetime=datetime.datetime(2011,12,1))
Of course you could omit the namespace = {} and the in namespace / , namespace parts, but then, the code in file.py might actually change other variables in your shell.
Comments
you can import a folder doing
import path1
and then call simply the script doing:
path1.path2.file.run(...)
otherwhise if you do not want to include all the other stuff within the directory you can try with
from path1.path2.file import run
in this case you have only to call:
run()
Cheers,