How to Import from parent directory Python - python

I am trying to import a file from the main directory using python. I tried several methods but no luck :(.
My file directory
|_ api
|__init__.py
|_api1.py
|_api2.py
|_api3.py
|_api4.py
|_api5.py
|_api6.py
|__init__.py
|_api.py
|_db_ops.py
Challenge
I am trying to import some methods of api.py into api1.py and api2.py.
The solutions I have found were:
1. Add __ini__.py file
I have added them as you can see but did not work.
2. import using `import api`
did not worked rather throws an error **ModuleNotFoundError**
3. import using 'from . import api'
throws an error "cannot import from unknown module"
4. even tried to create a parent folder **test** and then tried with import test.apicall but still did not worked!
Any help.
Thanks

first of all, the file name is __init__.py and not __ini__.py.
by default, you only can import directory from the same level or below where you are using the python command.
example:
myproject/
project/
__init__.py
foo.py
bar.py
if the terminal in myproject and i run python project/foo.py, foo can import bar.py , but if i am myproject/project and i run python foo.py, foo cannot import bar.py
to change the default you can use
import sys
sys.path.append('path of my dir')

It depends on what you want to do. If you want to run a script in a lower-level folder, Python will not let you do it. On the other hand, let's say for simplicity you have the folder structure
mypackage/
subpackage/
__init__.py
api1.py
__init__.py
api.py
If api.py looks like the following
def foo(a):
print(a)
then in api1.py you can have a relative import like
from ..api import foo as f
Then you can't, however, run api1.py as a script, but you can use f as a function to extend things in api1.py or write a script with the content
from mypackage.subpackage.api1 import f
so in that case, it will look like the function foo was in api1.py.
I'll note that this was heavily inspired by the Python-documentation on relative imports... (https://docs.python.org/3/reference/import.html)

Related

Run python script from outer directory [duplicate]

How do I import files in Python? I want to import:
a file (e.g. file.py)
a folder
a file dynamically at runtime, based on user input
one specific part of a file (e.g. a single function)
There are many ways to import a python file, all with their pros and cons.
Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.
I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #7
Example 1, Import a python module with python interpreter:
Put this in /home/el/foo/fox.py:
def what_does_the_fox_say():
print("vixens cry")
Get into the python interpreter:
el#apollo:/home/el/foo$ python
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
>>> import fox
>>> fox.what_does_the_fox_say()
vixens cry
>>>
You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.
Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:
Put this in /home/el/foo2/mylib.py:
def moobar():
print("hi")
Put this in /home/el/foo2/main.py:
execfile("/home/el/foo2/mylib.py")
moobar()
run the file:
el#apollo:/home/el/foo$ python main.py
hi
The function moobar was imported from mylib.py and made available in main.py
Example 3, Use from ... import ... functionality:
Put this in /home/el/foo3/chekov.py:
def question():
print "where are the nuclear wessels?"
Put this in /home/el/foo3/main.py:
from chekov import question
question()
Run it like this:
el#apollo:/home/el/foo3$ python main.py
where are the nuclear wessels?
If you defined other functions in chekov.py, they would not be available unless you import *
Example 4, Import riaa.py if it's in a different file location from where it is imported
Put this in /home/el/foo4/stuff/riaa.py:
def watchout():
print "computers are transforming into a noose and a yoke for humans"
Put this in /home/el/foo4/main.py:
import sys
import os
sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
from riaa import *
watchout()
Run it:
el#apollo:/home/el/foo4$ python main.py
computers are transforming into a noose and a yoke for humans
That imports everything in the foreign file from a different directory.
Example 5, use os.system("python yourfile.py")
import os
os.system("python yourfile.py")
Example 6, import your file via piggybacking the python startuphook:
Update: This example used to work for both python2 and 3, but now only works for python2. python3 got rid of this user startuphook feature set because it was abused by low-skill python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for python3, you'll have to get more creative. If I tell you how to do it, python developers will disable that feature set as well, so you're on your own.
See: https://docs.python.org/2/library/user.html
Put this code into your home directory in ~/.pythonrc.py
class secretclass:
def secretmessage(cls, myarg):
return myarg + " is if.. up in the sky, the sky"
secretmessage = classmethod( secretmessage )
def skycake(cls):
return "cookie and sky pie people can't go up and "
skycake = classmethod( skycake )
Put this code into your main.py (can be anywhere):
import user
msg = "The only way skycake tates good"
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")
Run it, you should get this:
$ python main.py
The only way skycake tates good is if.. up in the sky,
the skycookie and sky pie people can't go up and have the sky pie!
SKYCAKE!
If you get an error here: ModuleNotFoundError: No module named 'user' then it means you're using python3, startuphooks are disabled there by default.
Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.
Example 7, Most Robust: Import files in python with the bare import command:
Make a new directory /home/el/foo5/
Make a new directory /home/el/foo5/herp
Make an empty file named __init__.py under herp:
el#apollo:/home/el/foo5/herp$ touch __init__.py
el#apollo:/home/el/foo5/herp$ ls
__init__.py
Make a new directory /home/el/foo5/herp/derp
Under derp, make another __init__.py file:
el#apollo:/home/el/foo5/herp/derp$ touch __init__.py
el#apollo:/home/el/foo5/herp/derp$ ls
__init__.py
Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:
def skycake():
print "SkyCake evolves to stay just beyond the cognitive reach of " +
"the bulk of men. SKYCAKE!!"
The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;
from herp.derp.yolo import skycake
skycake()
Run it:
el#apollo:/home/el/foo5$ python main.py
SkyCake evolves to stay just beyond the cognitive reach of the bulk
of men. SKYCAKE!!
The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.
If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131
importlib was added to Python 3 to programmatically import a module.
import importlib
moduleName = input('Enter module name:')
importlib.import_module(moduleName)
The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.
In python 2.x:
Just import file without the .py extension
A folder can be marked as a package, by adding an empty __init__.py file
You can use the __import__ function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))
Type help(__import__) for more details.
First case
You want to import file A.py in file B.py, these two files are in the same folder, like this:
.
├── A.py
└── B.py
You can do this in file B.py:
import A
or
from A import *
or
from A import THINGS_YOU_WANT_TO_IMPORT_IN_A
Then you will be able to use all the functions of file A.py in file B.py
Second case
You want to import file folder/A.py in file B.py, these two files are not in the same folder, like this:
.
├── B.py
└── folder
└── A.py
You can do this in file B.py:
import folder.A
or
from folder.A import *
or
from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A
Then you will be able to use all the functions of file A.py in file B.py
Summary
In the first case, file A.py is a module that you imports in file B.py, you used the syntax import module_name.
In the second case, folder is the package that contains the module A.py, you used the syntax import package_name.module_name.
For more info on packages and modules, consult this link.
To import a specific Python file at 'runtime' with a known name:
import os
import sys
...
scriptpath = "../Test/"
# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))
# Do the import
import MyModule
You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type
from root.parent.folder.file import variable, class, whatever
Import doc .. -- Link for reference
The __init__.py files are required to make Python treat the directories as containing packages, this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.
__init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.
mydir/spam/__init__.py
mydir/spam/module.py
import spam.module
or
from spam import module
from file import function_name ######## Importing specific function
function_name() ######## Calling function
and
import file ######## Importing whole package
file.function1_name() ######## Calling function
file.function2_name() ######## Calling function
Here are the two simple ways I have understood by now and make sure your "file.py" file which you want to import as a library is present in your current directory only.
If the function defined is in a file x.py:
def greet():
print('Hello! How are you?')
In the file where you are importing the function, write this:
from x import greet
This is useful if you do not wish to import all the functions in a file.
I'd like to add this note I don't very clearly elsewhere; inside a module/package, when loading from files, the module/package name must be prefixed with the mymodule. Imagine mymodule being layout like this:
/main.py
/mymodule
/__init__.py
/somefile.py
/otherstuff.py
When loading somefile.py/otherstuff.py from __init__.py the contents should look like:
from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc
the best way to import .py files is by way of __init__.py. the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.
this post by Mike Grouchy is a great explanation of __init__.py and its use for making, importing, and setting up python packages.
import sys
#print(sys.path)
sys.path.append('../input/tokenization')
import tokenization
To import any .py file, you can use above code.
First append the path and then import
Note:'../input/tokenization' directory contains tokenization.py file
Using Python 3.5 or later, you can use importlib.util to directly import a .py file in an arbitrary location as a module without needing to modify sys.path.
import importlib.util
import sys
def load_module(file_name, module_name)
spec = importlib.util.spec_from_file_location(module_name, file_name)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module
The file_name parameter must be a string or a path-like object. The module_name parameter is required because all loaded Python modules must have a (dotted) module name (like sys, importlib, or importlib.util), but you can choose any available name you want for this new module.
You can use this function like this:
my_module = load_module("file.py", "mymod")
After it has been imported once into the Python process using the load_module() function, the module will be importable using the module name given to it.
file.py:
print(f"file.py was imported as {__name__}")
one.py:
print(f"one.py was imported as {__name__}")
load_module("file.py", "mymod")
import two
two.py:
print(f"two.py was imported as {__name__})")
import mymod
Given the files above, you can run the following command to see how file.py became importable.
$ python3 -m one
one.py was imported as __main__
two.py was imported as two
file.py was imported as mymod
This answer is based on the official Python documentation: importlib: Importing a source file directly.
How I import is import the file and use shorthand of it's name.
import DoStuff.py as DS
DS.main()
Don't forget that your importing file MUST BE named with .py extension
There are couple of ways of including your python script with name abc.py
e.g. if your file is called abc.py (import abc)
Limitation is that your file should be present in the same location where your calling python script is.
import abc
e.g. if your python file is inside the Windows folder. Windows folder is present at the same location where your calling python script is.
from folder import abc
Incase abc.py script is available insider internal_folder which is present inside folder
from folder.internal_folder import abc
As answered by James above, in case your file is at some fixed location
import os
import sys
scriptpath = "../Test/MyModule.py"
sys.path.append(os.path.abspath(scriptpath))
import MyModule
In case your python script gets updated and you don't want to upload - use these statements for auto refresh. Bonus :)
%load_ext autoreload
%autoreload 2
In case the module you want to import is not in a sub-directory, then try the following and run app.py from the deepest common parent directory:
Directory Structure:
/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json
In app.py, append path of client to sys.path:
import os, sys, inspect
sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()
Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)
# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")
Run
user#host:/path/to/common_dir$ python3 application/app.py
This solution works for me in cli, as well as PyCharm.
This is how I did to call a function from a python file, that is flexible for me to call any functions.
import os, importlib, sys
def callfunc(myfile, myfunc, *args):
pathname, filename = os.path.split(myfile)
sys.path.append(os.path.abspath(pathname))
modname = os.path.splitext(filename)[0]
mymod = importlib.import_module(modname)
result = getattr(mymod, myfunc)(*args)
return result
result = callfunc("pathto/myfile.py", "myfunc", arg1, arg2)
Just to import python file in another python file
lets say I have helper.py python file which has a display function like,
def display():
print("I'm working sundar gsv")
Now in app.py, you can use the display function,
import helper
helper.display()
The output,
I'm working sundar gsv
NOTE: No need to specify the .py extension.
One very unknown feature of Python is the ability to import zip files:
library.zip
|-library
|--__init__.py
The file __init__.py of the package contains the following:
def dummy():
print 'Testing things out...'
We can write another script which can import a package from the zip archive. It is only necessary to add the zip file to the sys.path.
import sys
sys.path.append(r'library.zip')
import library
def run():
library.dummy()
run()
This helped me to structure my Python project with Visual Studio Code.
The problem could be caused when you don't declare __init__.py inside the directory. And the directory becomes implicit namespace package. Here is a nice summary about Python imports and project structure.
Also if you want to use the Visual Studio Code run button in the top bar with a script which is not inside the main package, you may try to run console from the actual directory.
For example, you want to execute an opened test_game_item.py from the tests package and you have Visual Studio Code opened in omission (main package) directory:
├── omission
│ ├── app.py
│ ├── common
│ │ ├── classproperty.py
│ │ ├── constants.py
│ │ ├── game_enums.py
│ │ └── __init__.py
│ ├── game
│ │ ├── content_loader.py
│ │ ├── game_item.py
│ │ ├── game_round.py
│ │ ├── __init__.py
│ │ └── timer.py
│ ├── __init__.py
│ ├── __main__.py
│ ├── resources
│ └── tests
│ ├── __init__.py
│ ├── test_game_item.py
│ ├── test_game_round_settings.py
│ ├── test_scoreboard.py
│ ├── test_settings.py
│ ├── test_test.py
│ └── test_timer.py
├── pylintrc
├── README.md
└── .gitignore
The directory structure is from [2].
You can try set this:
(Windows) Ctrl + Shift + P → Preferences: Open Settings (JSON).
Add this line to your user settings:
"python.terminal.executeInFileDir": true
A more comprehensive answer also for other systems is in this question.
This may sound crazy but you can just create a symbolic link to the file you want to import if you're just creating a wrapper script to it.
You can also do this: from filename import something
example: from client import Client
Note that you do not need the .py .pyw .pyui extension.
There are many ways, as listed above, but I find that I just want to import he contents of a file, and don't want to have to write lines and lines and have to import other modules. So, I came up with a way to get the contents of a file, even with the dot syntax (file.property) as opposed to merging the imported file with yours.
First of all, here is my file which I'll import, data.py
testString= "A string literal to import and test with"
Note: You could use the .txt extension instead.
In mainfile.py, start by opening and getting the contents.
#!usr/bin/env python3
Data=open('data.txt','r+').read()
Now you have the contents as a string, but trying to access data.testString will cause an error, as data is an instance of the str class, and even if it does have a property testString it will not do what you expected.
Next, create a class. For instance (pun intended), ImportedFile
class ImportedFile:
And put this into it (with the appropriate indentation):
exec(data)
And finally, re-assign data like so:
data=ImportedFile()
And that's it! Just access like you would for any-other module, typing print(data.testString) will print to the console A string literal to import and test with.
If, however, you want the equivalent of from mod import * just drop the class, instance assignment, and de-dent the exec.
Hope this helps:)
-Benji
from y import *
Say you have a file x and y.
You want to import y file to x.
then go to your x file and place the above command. To test this just put a print function in your y file and when your import was successful then in x file it should print it.

Best way to import a package located in a sibling directory

My file stucture is :
top\
my_package\
__init__.py
functions.py
scripts\
test.py
main.py
I would like to import the content of functions.py in test.py.
In main.py, I can import functions.py with from my_package.functions import ....
I was expecting to be able to import functions.py in test.py with something like from ..my_package.functions import ... but it raises the following error :
SystemError: Parent module '' not loaded, cannot perform relative import
top directory shoudln't be a package because I want to be able to run main.py without being running a script in a package.
What is the proper/pythonic way import functions.py from test.py ?
I could add my_package to the PYTHONPATH, but my code would be less portable. I'm using Python 3.5
This is happening because as far as python is concerned my_package and scripts directories are not related to each other.
To solve your problem you can add __init__.py to your top directory and try using
from ..function import *

Import a list of modules in a file in Python [duplicate]

How do I import files in Python? I want to import:
a file (e.g. file.py)
a folder
a file dynamically at runtime, based on user input
one specific part of a file (e.g. a single function)
There are many ways to import a python file, all with their pros and cons.
Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.
I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #7
Example 1, Import a python module with python interpreter:
Put this in /home/el/foo/fox.py:
def what_does_the_fox_say():
print("vixens cry")
Get into the python interpreter:
el#apollo:/home/el/foo$ python
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
>>> import fox
>>> fox.what_does_the_fox_say()
vixens cry
>>>
You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.
Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:
Put this in /home/el/foo2/mylib.py:
def moobar():
print("hi")
Put this in /home/el/foo2/main.py:
execfile("/home/el/foo2/mylib.py")
moobar()
run the file:
el#apollo:/home/el/foo$ python main.py
hi
The function moobar was imported from mylib.py and made available in main.py
Example 3, Use from ... import ... functionality:
Put this in /home/el/foo3/chekov.py:
def question():
print "where are the nuclear wessels?"
Put this in /home/el/foo3/main.py:
from chekov import question
question()
Run it like this:
el#apollo:/home/el/foo3$ python main.py
where are the nuclear wessels?
If you defined other functions in chekov.py, they would not be available unless you import *
Example 4, Import riaa.py if it's in a different file location from where it is imported
Put this in /home/el/foo4/stuff/riaa.py:
def watchout():
print "computers are transforming into a noose and a yoke for humans"
Put this in /home/el/foo4/main.py:
import sys
import os
sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
from riaa import *
watchout()
Run it:
el#apollo:/home/el/foo4$ python main.py
computers are transforming into a noose and a yoke for humans
That imports everything in the foreign file from a different directory.
Example 5, use os.system("python yourfile.py")
import os
os.system("python yourfile.py")
Example 6, import your file via piggybacking the python startuphook:
Update: This example used to work for both python2 and 3, but now only works for python2. python3 got rid of this user startuphook feature set because it was abused by low-skill python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for python3, you'll have to get more creative. If I tell you how to do it, python developers will disable that feature set as well, so you're on your own.
See: https://docs.python.org/2/library/user.html
Put this code into your home directory in ~/.pythonrc.py
class secretclass:
def secretmessage(cls, myarg):
return myarg + " is if.. up in the sky, the sky"
secretmessage = classmethod( secretmessage )
def skycake(cls):
return "cookie and sky pie people can't go up and "
skycake = classmethod( skycake )
Put this code into your main.py (can be anywhere):
import user
msg = "The only way skycake tates good"
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")
Run it, you should get this:
$ python main.py
The only way skycake tates good is if.. up in the sky,
the skycookie and sky pie people can't go up and have the sky pie!
SKYCAKE!
If you get an error here: ModuleNotFoundError: No module named 'user' then it means you're using python3, startuphooks are disabled there by default.
Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.
Example 7, Most Robust: Import files in python with the bare import command:
Make a new directory /home/el/foo5/
Make a new directory /home/el/foo5/herp
Make an empty file named __init__.py under herp:
el#apollo:/home/el/foo5/herp$ touch __init__.py
el#apollo:/home/el/foo5/herp$ ls
__init__.py
Make a new directory /home/el/foo5/herp/derp
Under derp, make another __init__.py file:
el#apollo:/home/el/foo5/herp/derp$ touch __init__.py
el#apollo:/home/el/foo5/herp/derp$ ls
__init__.py
Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:
def skycake():
print "SkyCake evolves to stay just beyond the cognitive reach of " +
"the bulk of men. SKYCAKE!!"
The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;
from herp.derp.yolo import skycake
skycake()
Run it:
el#apollo:/home/el/foo5$ python main.py
SkyCake evolves to stay just beyond the cognitive reach of the bulk
of men. SKYCAKE!!
The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.
If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131
importlib was added to Python 3 to programmatically import a module.
import importlib
moduleName = input('Enter module name:')
importlib.import_module(moduleName)
The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.
In python 2.x:
Just import file without the .py extension
A folder can be marked as a package, by adding an empty __init__.py file
You can use the __import__ function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))
Type help(__import__) for more details.
First case
You want to import file A.py in file B.py, these two files are in the same folder, like this:
.
├── A.py
└── B.py
You can do this in file B.py:
import A
or
from A import *
or
from A import THINGS_YOU_WANT_TO_IMPORT_IN_A
Then you will be able to use all the functions of file A.py in file B.py
Second case
You want to import file folder/A.py in file B.py, these two files are not in the same folder, like this:
.
├── B.py
└── folder
└── A.py
You can do this in file B.py:
import folder.A
or
from folder.A import *
or
from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A
Then you will be able to use all the functions of file A.py in file B.py
Summary
In the first case, file A.py is a module that you imports in file B.py, you used the syntax import module_name.
In the second case, folder is the package that contains the module A.py, you used the syntax import package_name.module_name.
For more info on packages and modules, consult this link.
To import a specific Python file at 'runtime' with a known name:
import os
import sys
...
scriptpath = "../Test/"
# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))
# Do the import
import MyModule
You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type
from root.parent.folder.file import variable, class, whatever
Import doc .. -- Link for reference
The __init__.py files are required to make Python treat the directories as containing packages, this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.
__init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.
mydir/spam/__init__.py
mydir/spam/module.py
import spam.module
or
from spam import module
from file import function_name ######## Importing specific function
function_name() ######## Calling function
and
import file ######## Importing whole package
file.function1_name() ######## Calling function
file.function2_name() ######## Calling function
Here are the two simple ways I have understood by now and make sure your "file.py" file which you want to import as a library is present in your current directory only.
If the function defined is in a file x.py:
def greet():
print('Hello! How are you?')
In the file where you are importing the function, write this:
from x import greet
This is useful if you do not wish to import all the functions in a file.
I'd like to add this note I don't very clearly elsewhere; inside a module/package, when loading from files, the module/package name must be prefixed with the mymodule. Imagine mymodule being layout like this:
/main.py
/mymodule
/__init__.py
/somefile.py
/otherstuff.py
When loading somefile.py/otherstuff.py from __init__.py the contents should look like:
from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc
Using Python 3.5 or later, you can use importlib.util to directly import a .py file in an arbitrary location as a module without needing to modify sys.path.
import importlib.util
import sys
def load_module(file_name, module_name)
spec = importlib.util.spec_from_file_location(module_name, file_name)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module
The file_name parameter must be a string or a path-like object. The module_name parameter is required because all loaded Python modules must have a (dotted) module name (like sys, importlib, or importlib.util), but you can choose any available name you want for this new module.
You can use this function like this:
my_module = load_module("file.py", "mymod")
After it has been imported once into the Python process using the load_module() function, the module will be importable using the module name given to it.
file.py:
print(f"file.py was imported as {__name__}")
one.py:
print(f"one.py was imported as {__name__}")
load_module("file.py", "mymod")
import two
two.py:
print(f"two.py was imported as {__name__})")
import mymod
Given the files above, you can run the following command to see how file.py became importable.
$ python3 -m one
one.py was imported as __main__
two.py was imported as two
file.py was imported as mymod
This answer is based on the official Python documentation: importlib: Importing a source file directly.
the best way to import .py files is by way of __init__.py. the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.
this post by Mike Grouchy is a great explanation of __init__.py and its use for making, importing, and setting up python packages.
import sys
#print(sys.path)
sys.path.append('../input/tokenization')
import tokenization
To import any .py file, you can use above code.
First append the path and then import
Note:'../input/tokenization' directory contains tokenization.py file
How I import is import the file and use shorthand of it's name.
import DoStuff.py as DS
DS.main()
Don't forget that your importing file MUST BE named with .py extension
There are couple of ways of including your python script with name abc.py
e.g. if your file is called abc.py (import abc)
Limitation is that your file should be present in the same location where your calling python script is.
import abc
e.g. if your python file is inside the Windows folder. Windows folder is present at the same location where your calling python script is.
from folder import abc
Incase abc.py script is available insider internal_folder which is present inside folder
from folder.internal_folder import abc
As answered by James above, in case your file is at some fixed location
import os
import sys
scriptpath = "../Test/MyModule.py"
sys.path.append(os.path.abspath(scriptpath))
import MyModule
In case your python script gets updated and you don't want to upload - use these statements for auto refresh. Bonus :)
%load_ext autoreload
%autoreload 2
In case the module you want to import is not in a sub-directory, then try the following and run app.py from the deepest common parent directory:
Directory Structure:
/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json
In app.py, append path of client to sys.path:
import os, sys, inspect
sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()
Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)
# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")
Run
user#host:/path/to/common_dir$ python3 application/app.py
This solution works for me in cli, as well as PyCharm.
This is how I did to call a function from a python file, that is flexible for me to call any functions.
import os, importlib, sys
def callfunc(myfile, myfunc, *args):
pathname, filename = os.path.split(myfile)
sys.path.append(os.path.abspath(pathname))
modname = os.path.splitext(filename)[0]
mymod = importlib.import_module(modname)
result = getattr(mymod, myfunc)(*args)
return result
result = callfunc("pathto/myfile.py", "myfunc", arg1, arg2)
Just to import python file in another python file
lets say I have helper.py python file which has a display function like,
def display():
print("I'm working sundar gsv")
Now in app.py, you can use the display function,
import helper
helper.display()
The output,
I'm working sundar gsv
NOTE: No need to specify the .py extension.
One very unknown feature of Python is the ability to import zip files:
library.zip
|-library
|--__init__.py
The file __init__.py of the package contains the following:
def dummy():
print 'Testing things out...'
We can write another script which can import a package from the zip archive. It is only necessary to add the zip file to the sys.path.
import sys
sys.path.append(r'library.zip')
import library
def run():
library.dummy()
run()
This helped me to structure my Python project with Visual Studio Code.
The problem could be caused when you don't declare __init__.py inside the directory. And the directory becomes implicit namespace package. Here is a nice summary about Python imports and project structure.
Also if you want to use the Visual Studio Code run button in the top bar with a script which is not inside the main package, you may try to run console from the actual directory.
For example, you want to execute an opened test_game_item.py from the tests package and you have Visual Studio Code opened in omission (main package) directory:
├── omission
│ ├── app.py
│ ├── common
│ │ ├── classproperty.py
│ │ ├── constants.py
│ │ ├── game_enums.py
│ │ └── __init__.py
│ ├── game
│ │ ├── content_loader.py
│ │ ├── game_item.py
│ │ ├── game_round.py
│ │ ├── __init__.py
│ │ └── timer.py
│ ├── __init__.py
│ ├── __main__.py
│ ├── resources
│ └── tests
│ ├── __init__.py
│ ├── test_game_item.py
│ ├── test_game_round_settings.py
│ ├── test_scoreboard.py
│ ├── test_settings.py
│ ├── test_test.py
│ └── test_timer.py
├── pylintrc
├── README.md
└── .gitignore
The directory structure is from [2].
You can try set this:
(Windows) Ctrl + Shift + P → Preferences: Open Settings (JSON).
Add this line to your user settings:
"python.terminal.executeInFileDir": true
A more comprehensive answer also for other systems is in this question.
This may sound crazy but you can just create a symbolic link to the file you want to import if you're just creating a wrapper script to it.
You can also do this: from filename import something
example: from client import Client
Note that you do not need the .py .pyw .pyui extension.
There are many ways, as listed above, but I find that I just want to import he contents of a file, and don't want to have to write lines and lines and have to import other modules. So, I came up with a way to get the contents of a file, even with the dot syntax (file.property) as opposed to merging the imported file with yours.
First of all, here is my file which I'll import, data.py
testString= "A string literal to import and test with"
Note: You could use the .txt extension instead.
In mainfile.py, start by opening and getting the contents.
#!usr/bin/env python3
Data=open('data.txt','r+').read()
Now you have the contents as a string, but trying to access data.testString will cause an error, as data is an instance of the str class, and even if it does have a property testString it will not do what you expected.
Next, create a class. For instance (pun intended), ImportedFile
class ImportedFile:
And put this into it (with the appropriate indentation):
exec(data)
And finally, re-assign data like so:
data=ImportedFile()
And that's it! Just access like you would for any-other module, typing print(data.testString) will print to the console A string literal to import and test with.
If, however, you want the equivalent of from mod import * just drop the class, instance assignment, and de-dent the exec.
Hope this helps:)
-Benji
from y import *
Say you have a file x and y.
You want to import y file to x.
then go to your x file and place the above command. To test this just put a print function in your y file and when your import was successful then in x file it should print it.

python Call Tkinter Function from different python script [duplicate]

How do I import files in Python? I want to import:
a file (e.g. file.py)
a folder
a file dynamically at runtime, based on user input
one specific part of a file (e.g. a single function)
There are many ways to import a python file, all with their pros and cons.
Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.
I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #7
Example 1, Import a python module with python interpreter:
Put this in /home/el/foo/fox.py:
def what_does_the_fox_say():
print("vixens cry")
Get into the python interpreter:
el#apollo:/home/el/foo$ python
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
>>> import fox
>>> fox.what_does_the_fox_say()
vixens cry
>>>
You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.
Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:
Put this in /home/el/foo2/mylib.py:
def moobar():
print("hi")
Put this in /home/el/foo2/main.py:
execfile("/home/el/foo2/mylib.py")
moobar()
run the file:
el#apollo:/home/el/foo$ python main.py
hi
The function moobar was imported from mylib.py and made available in main.py
Example 3, Use from ... import ... functionality:
Put this in /home/el/foo3/chekov.py:
def question():
print "where are the nuclear wessels?"
Put this in /home/el/foo3/main.py:
from chekov import question
question()
Run it like this:
el#apollo:/home/el/foo3$ python main.py
where are the nuclear wessels?
If you defined other functions in chekov.py, they would not be available unless you import *
Example 4, Import riaa.py if it's in a different file location from where it is imported
Put this in /home/el/foo4/stuff/riaa.py:
def watchout():
print "computers are transforming into a noose and a yoke for humans"
Put this in /home/el/foo4/main.py:
import sys
import os
sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
from riaa import *
watchout()
Run it:
el#apollo:/home/el/foo4$ python main.py
computers are transforming into a noose and a yoke for humans
That imports everything in the foreign file from a different directory.
Example 5, use os.system("python yourfile.py")
import os
os.system("python yourfile.py")
Example 6, import your file via piggybacking the python startuphook:
Update: This example used to work for both python2 and 3, but now only works for python2. python3 got rid of this user startuphook feature set because it was abused by low-skill python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for python3, you'll have to get more creative. If I tell you how to do it, python developers will disable that feature set as well, so you're on your own.
See: https://docs.python.org/2/library/user.html
Put this code into your home directory in ~/.pythonrc.py
class secretclass:
def secretmessage(cls, myarg):
return myarg + " is if.. up in the sky, the sky"
secretmessage = classmethod( secretmessage )
def skycake(cls):
return "cookie and sky pie people can't go up and "
skycake = classmethod( skycake )
Put this code into your main.py (can be anywhere):
import user
msg = "The only way skycake tates good"
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")
Run it, you should get this:
$ python main.py
The only way skycake tates good is if.. up in the sky,
the skycookie and sky pie people can't go up and have the sky pie!
SKYCAKE!
If you get an error here: ModuleNotFoundError: No module named 'user' then it means you're using python3, startuphooks are disabled there by default.
Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.
Example 7, Most Robust: Import files in python with the bare import command:
Make a new directory /home/el/foo5/
Make a new directory /home/el/foo5/herp
Make an empty file named __init__.py under herp:
el#apollo:/home/el/foo5/herp$ touch __init__.py
el#apollo:/home/el/foo5/herp$ ls
__init__.py
Make a new directory /home/el/foo5/herp/derp
Under derp, make another __init__.py file:
el#apollo:/home/el/foo5/herp/derp$ touch __init__.py
el#apollo:/home/el/foo5/herp/derp$ ls
__init__.py
Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:
def skycake():
print "SkyCake evolves to stay just beyond the cognitive reach of " +
"the bulk of men. SKYCAKE!!"
The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;
from herp.derp.yolo import skycake
skycake()
Run it:
el#apollo:/home/el/foo5$ python main.py
SkyCake evolves to stay just beyond the cognitive reach of the bulk
of men. SKYCAKE!!
The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.
If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131
importlib was added to Python 3 to programmatically import a module.
import importlib
moduleName = input('Enter module name:')
importlib.import_module(moduleName)
The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.
In python 2.x:
Just import file without the .py extension
A folder can be marked as a package, by adding an empty __init__.py file
You can use the __import__ function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))
Type help(__import__) for more details.
First case
You want to import file A.py in file B.py, these two files are in the same folder, like this:
.
├── A.py
└── B.py
You can do this in file B.py:
import A
or
from A import *
or
from A import THINGS_YOU_WANT_TO_IMPORT_IN_A
Then you will be able to use all the functions of file A.py in file B.py
Second case
You want to import file folder/A.py in file B.py, these two files are not in the same folder, like this:
.
├── B.py
└── folder
└── A.py
You can do this in file B.py:
import folder.A
or
from folder.A import *
or
from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A
Then you will be able to use all the functions of file A.py in file B.py
Summary
In the first case, file A.py is a module that you imports in file B.py, you used the syntax import module_name.
In the second case, folder is the package that contains the module A.py, you used the syntax import package_name.module_name.
For more info on packages and modules, consult this link.
To import a specific Python file at 'runtime' with a known name:
import os
import sys
...
scriptpath = "../Test/"
# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))
# Do the import
import MyModule
You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type
from root.parent.folder.file import variable, class, whatever
Import doc .. -- Link for reference
The __init__.py files are required to make Python treat the directories as containing packages, this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.
__init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.
mydir/spam/__init__.py
mydir/spam/module.py
import spam.module
or
from spam import module
from file import function_name ######## Importing specific function
function_name() ######## Calling function
and
import file ######## Importing whole package
file.function1_name() ######## Calling function
file.function2_name() ######## Calling function
Here are the two simple ways I have understood by now and make sure your "file.py" file which you want to import as a library is present in your current directory only.
If the function defined is in a file x.py:
def greet():
print('Hello! How are you?')
In the file where you are importing the function, write this:
from x import greet
This is useful if you do not wish to import all the functions in a file.
I'd like to add this note I don't very clearly elsewhere; inside a module/package, when loading from files, the module/package name must be prefixed with the mymodule. Imagine mymodule being layout like this:
/main.py
/mymodule
/__init__.py
/somefile.py
/otherstuff.py
When loading somefile.py/otherstuff.py from __init__.py the contents should look like:
from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc
Using Python 3.5 or later, you can use importlib.util to directly import a .py file in an arbitrary location as a module without needing to modify sys.path.
import importlib.util
import sys
def load_module(file_name, module_name)
spec = importlib.util.spec_from_file_location(module_name, file_name)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module
The file_name parameter must be a string or a path-like object. The module_name parameter is required because all loaded Python modules must have a (dotted) module name (like sys, importlib, or importlib.util), but you can choose any available name you want for this new module.
You can use this function like this:
my_module = load_module("file.py", "mymod")
After it has been imported once into the Python process using the load_module() function, the module will be importable using the module name given to it.
file.py:
print(f"file.py was imported as {__name__}")
one.py:
print(f"one.py was imported as {__name__}")
load_module("file.py", "mymod")
import two
two.py:
print(f"two.py was imported as {__name__})")
import mymod
Given the files above, you can run the following command to see how file.py became importable.
$ python3 -m one
one.py was imported as __main__
two.py was imported as two
file.py was imported as mymod
This answer is based on the official Python documentation: importlib: Importing a source file directly.
the best way to import .py files is by way of __init__.py. the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.
this post by Mike Grouchy is a great explanation of __init__.py and its use for making, importing, and setting up python packages.
import sys
#print(sys.path)
sys.path.append('../input/tokenization')
import tokenization
To import any .py file, you can use above code.
First append the path and then import
Note:'../input/tokenization' directory contains tokenization.py file
How I import is import the file and use shorthand of it's name.
import DoStuff.py as DS
DS.main()
Don't forget that your importing file MUST BE named with .py extension
There are couple of ways of including your python script with name abc.py
e.g. if your file is called abc.py (import abc)
Limitation is that your file should be present in the same location where your calling python script is.
import abc
e.g. if your python file is inside the Windows folder. Windows folder is present at the same location where your calling python script is.
from folder import abc
Incase abc.py script is available insider internal_folder which is present inside folder
from folder.internal_folder import abc
As answered by James above, in case your file is at some fixed location
import os
import sys
scriptpath = "../Test/MyModule.py"
sys.path.append(os.path.abspath(scriptpath))
import MyModule
In case your python script gets updated and you don't want to upload - use these statements for auto refresh. Bonus :)
%load_ext autoreload
%autoreload 2
In case the module you want to import is not in a sub-directory, then try the following and run app.py from the deepest common parent directory:
Directory Structure:
/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json
In app.py, append path of client to sys.path:
import os, sys, inspect
sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()
Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)
# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")
Run
user#host:/path/to/common_dir$ python3 application/app.py
This solution works for me in cli, as well as PyCharm.
This is how I did to call a function from a python file, that is flexible for me to call any functions.
import os, importlib, sys
def callfunc(myfile, myfunc, *args):
pathname, filename = os.path.split(myfile)
sys.path.append(os.path.abspath(pathname))
modname = os.path.splitext(filename)[0]
mymod = importlib.import_module(modname)
result = getattr(mymod, myfunc)(*args)
return result
result = callfunc("pathto/myfile.py", "myfunc", arg1, arg2)
Just to import python file in another python file
lets say I have helper.py python file which has a display function like,
def display():
print("I'm working sundar gsv")
Now in app.py, you can use the display function,
import helper
helper.display()
The output,
I'm working sundar gsv
NOTE: No need to specify the .py extension.
One very unknown feature of Python is the ability to import zip files:
library.zip
|-library
|--__init__.py
The file __init__.py of the package contains the following:
def dummy():
print 'Testing things out...'
We can write another script which can import a package from the zip archive. It is only necessary to add the zip file to the sys.path.
import sys
sys.path.append(r'library.zip')
import library
def run():
library.dummy()
run()
This helped me to structure my Python project with Visual Studio Code.
The problem could be caused when you don't declare __init__.py inside the directory. And the directory becomes implicit namespace package. Here is a nice summary about Python imports and project structure.
Also if you want to use the Visual Studio Code run button in the top bar with a script which is not inside the main package, you may try to run console from the actual directory.
For example, you want to execute an opened test_game_item.py from the tests package and you have Visual Studio Code opened in omission (main package) directory:
├── omission
│ ├── app.py
│ ├── common
│ │ ├── classproperty.py
│ │ ├── constants.py
│ │ ├── game_enums.py
│ │ └── __init__.py
│ ├── game
│ │ ├── content_loader.py
│ │ ├── game_item.py
│ │ ├── game_round.py
│ │ ├── __init__.py
│ │ └── timer.py
│ ├── __init__.py
│ ├── __main__.py
│ ├── resources
│ └── tests
│ ├── __init__.py
│ ├── test_game_item.py
│ ├── test_game_round_settings.py
│ ├── test_scoreboard.py
│ ├── test_settings.py
│ ├── test_test.py
│ └── test_timer.py
├── pylintrc
├── README.md
└── .gitignore
The directory structure is from [2].
You can try set this:
(Windows) Ctrl + Shift + P → Preferences: Open Settings (JSON).
Add this line to your user settings:
"python.terminal.executeInFileDir": true
A more comprehensive answer also for other systems is in this question.
This may sound crazy but you can just create a symbolic link to the file you want to import if you're just creating a wrapper script to it.
You can also do this: from filename import something
example: from client import Client
Note that you do not need the .py .pyw .pyui extension.
There are many ways, as listed above, but I find that I just want to import he contents of a file, and don't want to have to write lines and lines and have to import other modules. So, I came up with a way to get the contents of a file, even with the dot syntax (file.property) as opposed to merging the imported file with yours.
First of all, here is my file which I'll import, data.py
testString= "A string literal to import and test with"
Note: You could use the .txt extension instead.
In mainfile.py, start by opening and getting the contents.
#!usr/bin/env python3
Data=open('data.txt','r+').read()
Now you have the contents as a string, but trying to access data.testString will cause an error, as data is an instance of the str class, and even if it does have a property testString it will not do what you expected.
Next, create a class. For instance (pun intended), ImportedFile
class ImportedFile:
And put this into it (with the appropriate indentation):
exec(data)
And finally, re-assign data like so:
data=ImportedFile()
And that's it! Just access like you would for any-other module, typing print(data.testString) will print to the console A string literal to import and test with.
If, however, you want the equivalent of from mod import * just drop the class, instance assignment, and de-dent the exec.
Hope this helps:)
-Benji
from y import *
Say you have a file x and y.
You want to import y file to x.
then go to your x file and place the above command. To test this just put a print function in your y file and when your import was successful then in x file it should print it.

How do I import other Python files?

How do I import files in Python? I want to import:
a file (e.g. file.py)
a folder
a file dynamically at runtime, based on user input
one specific part of a file (e.g. a single function)
There are many ways to import a python file, all with their pros and cons.
Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.
I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #7
Example 1, Import a python module with python interpreter:
Put this in /home/el/foo/fox.py:
def what_does_the_fox_say():
print("vixens cry")
Get into the python interpreter:
el#apollo:/home/el/foo$ python
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
>>> import fox
>>> fox.what_does_the_fox_say()
vixens cry
>>>
You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.
Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:
Put this in /home/el/foo2/mylib.py:
def moobar():
print("hi")
Put this in /home/el/foo2/main.py:
execfile("/home/el/foo2/mylib.py")
moobar()
run the file:
el#apollo:/home/el/foo$ python main.py
hi
The function moobar was imported from mylib.py and made available in main.py
Example 3, Use from ... import ... functionality:
Put this in /home/el/foo3/chekov.py:
def question():
print "where are the nuclear wessels?"
Put this in /home/el/foo3/main.py:
from chekov import question
question()
Run it like this:
el#apollo:/home/el/foo3$ python main.py
where are the nuclear wessels?
If you defined other functions in chekov.py, they would not be available unless you import *
Example 4, Import riaa.py if it's in a different file location from where it is imported
Put this in /home/el/foo4/stuff/riaa.py:
def watchout():
print "computers are transforming into a noose and a yoke for humans"
Put this in /home/el/foo4/main.py:
import sys
import os
sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
from riaa import *
watchout()
Run it:
el#apollo:/home/el/foo4$ python main.py
computers are transforming into a noose and a yoke for humans
That imports everything in the foreign file from a different directory.
Example 5, use os.system("python yourfile.py")
import os
os.system("python yourfile.py")
Example 6, import your file via piggybacking the python startuphook:
Update: This example used to work for both python2 and 3, but now only works for python2. python3 got rid of this user startuphook feature set because it was abused by low-skill python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for python3, you'll have to get more creative. If I tell you how to do it, python developers will disable that feature set as well, so you're on your own.
See: https://docs.python.org/2/library/user.html
Put this code into your home directory in ~/.pythonrc.py
class secretclass:
def secretmessage(cls, myarg):
return myarg + " is if.. up in the sky, the sky"
secretmessage = classmethod( secretmessage )
def skycake(cls):
return "cookie and sky pie people can't go up and "
skycake = classmethod( skycake )
Put this code into your main.py (can be anywhere):
import user
msg = "The only way skycake tates good"
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")
Run it, you should get this:
$ python main.py
The only way skycake tates good is if.. up in the sky,
the skycookie and sky pie people can't go up and have the sky pie!
SKYCAKE!
If you get an error here: ModuleNotFoundError: No module named 'user' then it means you're using python3, startuphooks are disabled there by default.
Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.
Example 7, Most Robust: Import files in python with the bare import command:
Make a new directory /home/el/foo5/
Make a new directory /home/el/foo5/herp
Make an empty file named __init__.py under herp:
el#apollo:/home/el/foo5/herp$ touch __init__.py
el#apollo:/home/el/foo5/herp$ ls
__init__.py
Make a new directory /home/el/foo5/herp/derp
Under derp, make another __init__.py file:
el#apollo:/home/el/foo5/herp/derp$ touch __init__.py
el#apollo:/home/el/foo5/herp/derp$ ls
__init__.py
Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:
def skycake():
print "SkyCake evolves to stay just beyond the cognitive reach of " +
"the bulk of men. SKYCAKE!!"
The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;
from herp.derp.yolo import skycake
skycake()
Run it:
el#apollo:/home/el/foo5$ python main.py
SkyCake evolves to stay just beyond the cognitive reach of the bulk
of men. SKYCAKE!!
The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.
If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131
importlib was added to Python 3 to programmatically import a module.
import importlib
moduleName = input('Enter module name:')
importlib.import_module(moduleName)
The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.
In python 2.x:
Just import file without the .py extension
A folder can be marked as a package, by adding an empty __init__.py file
You can use the __import__ function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))
Type help(__import__) for more details.
First case
You want to import file A.py in file B.py, these two files are in the same folder, like this:
.
├── A.py
└── B.py
You can do this in file B.py:
import A
or
from A import *
or
from A import THINGS_YOU_WANT_TO_IMPORT_IN_A
Then you will be able to use all the functions of file A.py in file B.py
Second case
You want to import file folder/A.py in file B.py, these two files are not in the same folder, like this:
.
├── B.py
└── folder
└── A.py
You can do this in file B.py:
import folder.A
or
from folder.A import *
or
from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A
Then you will be able to use all the functions of file A.py in file B.py
Summary
In the first case, file A.py is a module that you imports in file B.py, you used the syntax import module_name.
In the second case, folder is the package that contains the module A.py, you used the syntax import package_name.module_name.
For more info on packages and modules, consult this link.
To import a specific Python file at 'runtime' with a known name:
import os
import sys
...
scriptpath = "../Test/"
# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))
# Do the import
import MyModule
You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type
from root.parent.folder.file import variable, class, whatever
Import doc .. -- Link for reference
The __init__.py files are required to make Python treat the directories as containing packages, this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.
__init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.
mydir/spam/__init__.py
mydir/spam/module.py
import spam.module
or
from spam import module
from file import function_name ######## Importing specific function
function_name() ######## Calling function
and
import file ######## Importing whole package
file.function1_name() ######## Calling function
file.function2_name() ######## Calling function
Here are the two simple ways I have understood by now and make sure your "file.py" file which you want to import as a library is present in your current directory only.
If the function defined is in a file x.py:
def greet():
print('Hello! How are you?')
In the file where you are importing the function, write this:
from x import greet
This is useful if you do not wish to import all the functions in a file.
I'd like to add this note I don't very clearly elsewhere; inside a module/package, when loading from files, the module/package name must be prefixed with the mymodule. Imagine mymodule being layout like this:
/main.py
/mymodule
/__init__.py
/somefile.py
/otherstuff.py
When loading somefile.py/otherstuff.py from __init__.py the contents should look like:
from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc
Using Python 3.5 or later, you can use importlib.util to directly import a .py file in an arbitrary location as a module without needing to modify sys.path.
import importlib.util
import sys
def load_module(file_name, module_name)
spec = importlib.util.spec_from_file_location(module_name, file_name)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module
The file_name parameter must be a string or a path-like object. The module_name parameter is required because all loaded Python modules must have a (dotted) module name (like sys, importlib, or importlib.util), but you can choose any available name you want for this new module.
You can use this function like this:
my_module = load_module("file.py", "mymod")
After it has been imported once into the Python process using the load_module() function, the module will be importable using the module name given to it.
file.py:
print(f"file.py was imported as {__name__}")
one.py:
print(f"one.py was imported as {__name__}")
load_module("file.py", "mymod")
import two
two.py:
print(f"two.py was imported as {__name__})")
import mymod
Given the files above, you can run the following command to see how file.py became importable.
$ python3 -m one
one.py was imported as __main__
two.py was imported as two
file.py was imported as mymod
This answer is based on the official Python documentation: importlib: Importing a source file directly.
the best way to import .py files is by way of __init__.py. the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.
this post by Mike Grouchy is a great explanation of __init__.py and its use for making, importing, and setting up python packages.
import sys
#print(sys.path)
sys.path.append('../input/tokenization')
import tokenization
To import any .py file, you can use above code.
First append the path and then import
Note:'../input/tokenization' directory contains tokenization.py file
How I import is import the file and use shorthand of it's name.
import DoStuff.py as DS
DS.main()
Don't forget that your importing file MUST BE named with .py extension
There are couple of ways of including your python script with name abc.py
e.g. if your file is called abc.py (import abc)
Limitation is that your file should be present in the same location where your calling python script is.
import abc
e.g. if your python file is inside the Windows folder. Windows folder is present at the same location where your calling python script is.
from folder import abc
Incase abc.py script is available insider internal_folder which is present inside folder
from folder.internal_folder import abc
As answered by James above, in case your file is at some fixed location
import os
import sys
scriptpath = "../Test/MyModule.py"
sys.path.append(os.path.abspath(scriptpath))
import MyModule
In case your python script gets updated and you don't want to upload - use these statements for auto refresh. Bonus :)
%load_ext autoreload
%autoreload 2
In case the module you want to import is not in a sub-directory, then try the following and run app.py from the deepest common parent directory:
Directory Structure:
/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json
In app.py, append path of client to sys.path:
import os, sys, inspect
sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()
Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)
# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")
Run
user#host:/path/to/common_dir$ python3 application/app.py
This solution works for me in cli, as well as PyCharm.
This is how I did to call a function from a python file, that is flexible for me to call any functions.
import os, importlib, sys
def callfunc(myfile, myfunc, *args):
pathname, filename = os.path.split(myfile)
sys.path.append(os.path.abspath(pathname))
modname = os.path.splitext(filename)[0]
mymod = importlib.import_module(modname)
result = getattr(mymod, myfunc)(*args)
return result
result = callfunc("pathto/myfile.py", "myfunc", arg1, arg2)
Just to import python file in another python file
lets say I have helper.py python file which has a display function like,
def display():
print("I'm working sundar gsv")
Now in app.py, you can use the display function,
import helper
helper.display()
The output,
I'm working sundar gsv
NOTE: No need to specify the .py extension.
One very unknown feature of Python is the ability to import zip files:
library.zip
|-library
|--__init__.py
The file __init__.py of the package contains the following:
def dummy():
print 'Testing things out...'
We can write another script which can import a package from the zip archive. It is only necessary to add the zip file to the sys.path.
import sys
sys.path.append(r'library.zip')
import library
def run():
library.dummy()
run()
This helped me to structure my Python project with Visual Studio Code.
The problem could be caused when you don't declare __init__.py inside the directory. And the directory becomes implicit namespace package. Here is a nice summary about Python imports and project structure.
Also if you want to use the Visual Studio Code run button in the top bar with a script which is not inside the main package, you may try to run console from the actual directory.
For example, you want to execute an opened test_game_item.py from the tests package and you have Visual Studio Code opened in omission (main package) directory:
├── omission
│ ├── app.py
│ ├── common
│ │ ├── classproperty.py
│ │ ├── constants.py
│ │ ├── game_enums.py
│ │ └── __init__.py
│ ├── game
│ │ ├── content_loader.py
│ │ ├── game_item.py
│ │ ├── game_round.py
│ │ ├── __init__.py
│ │ └── timer.py
│ ├── __init__.py
│ ├── __main__.py
│ ├── resources
│ └── tests
│ ├── __init__.py
│ ├── test_game_item.py
│ ├── test_game_round_settings.py
│ ├── test_scoreboard.py
│ ├── test_settings.py
│ ├── test_test.py
│ └── test_timer.py
├── pylintrc
├── README.md
└── .gitignore
The directory structure is from [2].
You can try set this:
(Windows) Ctrl + Shift + P → Preferences: Open Settings (JSON).
Add this line to your user settings:
"python.terminal.executeInFileDir": true
A more comprehensive answer also for other systems is in this question.
This may sound crazy but you can just create a symbolic link to the file you want to import if you're just creating a wrapper script to it.
You can also do this: from filename import something
example: from client import Client
Note that you do not need the .py .pyw .pyui extension.
There are many ways, as listed above, but I find that I just want to import he contents of a file, and don't want to have to write lines and lines and have to import other modules. So, I came up with a way to get the contents of a file, even with the dot syntax (file.property) as opposed to merging the imported file with yours.
First of all, here is my file which I'll import, data.py
testString= "A string literal to import and test with"
Note: You could use the .txt extension instead.
In mainfile.py, start by opening and getting the contents.
#!usr/bin/env python3
Data=open('data.txt','r+').read()
Now you have the contents as a string, but trying to access data.testString will cause an error, as data is an instance of the str class, and even if it does have a property testString it will not do what you expected.
Next, create a class. For instance (pun intended), ImportedFile
class ImportedFile:
And put this into it (with the appropriate indentation):
exec(data)
And finally, re-assign data like so:
data=ImportedFile()
And that's it! Just access like you would for any-other module, typing print(data.testString) will print to the console A string literal to import and test with.
If, however, you want the equivalent of from mod import * just drop the class, instance assignment, and de-dent the exec.
Hope this helps:)
-Benji
from y import *
Say you have a file x and y.
You want to import y file to x.
then go to your x file and place the above command. To test this just put a print function in your y file and when your import was successful then in x file it should print it.

Categories

Resources