0

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

4

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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

first one getting AttributeError: 'module' object has no attribute 'path2'
Do you have an __init__.py file in the path1 directory AND path2 directory ?
0

Try the following:

from path1.path2.file import run

Comments

0

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

-1

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,

1 Comment

Doing "import some_package" won't import all subpackages/submodules from it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.