import file as module in Python - python

I wanted to make a cmd tool. I created two files, one named main.py, and the other named version.py
there are in the same directory
version.py:
import os
def pyVersion():
os.system("python --version")
main.py:
import version
version.pyVersion()
I think it should work, but when I run main.py, it prints:
File "C:\Users\User\PycharmProjects\cmd tool\main.py", line 1, in <module>
import version
ModuleNotFoundError: No module named 'version'

Normally Python should use folder C:\Users\User\PycharmProjects\cmd tool\ to search imported modules and you may have this folder even on list sys.path
But if it doesn't have this folder on list then you may add it manually before importing module.
import sys
# add at the end of list
#sys.path.append(r'C:\Users\User\PycharmProjects\cmd tool\')
# add at the beginning of list
sys.path.insert(0, r'C:\Users\User\PycharmProjects\cmd tool\')
import version
# ... code ...
To make it more universal you can use os to get this folder without hardcoding
import os
BASE = os.path.dirname(os.path.abspath(__file__))
print('BASE:', BASE)
import sys
sys.path.insert(0, BASE)
import version
# ... code ...

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.

change please the class name , and make the first letters uppercase
Version.py
def pyVersion():
os.system("python --version")
Main.py
import Version
Version.pyVersion()
and the code must work and he will give you a result Python version

Related

Python Import functions from own file

I have a problem. I created a script that uses a few functions, but now I have moved those functions in a folder named: include. The file is called: mylib.py, but when I use the following code:
import sys
sys.path.insert(0, 'include/')
import mylib
It gives an error: No module named 'mylib'. The main code is in the windows directory: Desktop/Python/ and the include file in: Desktop/Python/include/.
What am I doing wrong?
add an empty file __init__.py to the include folder to make it a package.
then import from it with:
from include import mylib
Replace the second line with this one:
sys.path.insert(0, '/Desktop/Python/include')

How to import Python file?

Sorry, this is definitely a duplicate, but I can't find the answer. I'm working in Python 3 and this is the structure of my app:
/home
common.py
australia/
new-south-wales/
fetch.py
I am in the home/ directory, running fetch.py. How can I import functions from common.py in that script?
I've set up fetch.py as follows:
from common import writeFile
But I get the following error:
File "australia/new-south-wales/fetch.py", line 8, in <module>
from common import writeFile
ModuleNotFoundError: No module named 'common'
If I just do python -c "from common import writeFile" I don't see an error.
Shouldn't the interpreter look in the current directory for modules?
before import your directories that need to be imported must have file __init__.py in that folder
#solution 1 (import in runtime)
To import a specific Python file at 'runtime' with a known name:
import os
import sys
script_dir = "/path/to/your/code/directory"
# Add the absolute directory path containing your
# module to the Python path
sys.path.append(os.path.abspath(script_dir))
import filename
#solution 2(add files to one of python libraries)
also as you have a common library for you can run
>>> import sys
>>> print sys.path
and see what directories you can put your code and use in every project.you can move your common package to one of this directories and treat it like a normal package.for example for common.py if you put it in one root directory of one of this directory you can import like import common
#solution 3(use relative import)
# from two parent above current directory import common
# every dot for one parent directory
from ... import common
and then go to parent directory and run
python -m home.australia.new-south-wales.fetch
From the description I'm assuming you're not running this as complete python package, just as separate files.
What you can do is use complete modules. This means adding empty __init__.py to directories with your code. You'll also have to change the name of new-south-wales to new_south_wales, since it needs to be a valid module name.
Assuming home is the name of your app, you should end up with:
home/
__init__.py
common.py
australia/
__init__.py
new_south_wales/
__init__.py
fetch.py
Next, you'll need a startup script for your app - this means either something simple like:
#!/usr/bin/env python
from australia.new_south_wales import fetch
fetch.your_main_function()
Or you can add a setup.py with a full package description. If you specify entry points and the script will be automatically created.
Now that you're starting your code in context of a package, your fetch.py can do:
from ..common import writeFile

python, import file under current folder from a file under other directory

I have a package which intends to import a file that user (me) provides
In c:\lib\calc.py
# some codes to find which file to import
filename = "A"
__import__(filename)
...
And I have a file c:\scripts\A.py
Note A.py is in a different folder than calc.py. Now I'm supposed to do this under command window
cd C:\scripts
python c:\lib\calc.py
but I get an error message
No module named A
A.py is in the current folder, why does python fail to find it? How can I make A.py available?
Thanks.
You can add the path to your scripts directory in your script calc.py so it can find the A.py module.
import sys
sys.path.append('C:\scripts')
If you are on Python version 2.7 or newer you can use the importlib package. The import_module function can accept an absolute path which, IIRC, does not need to be on your PYTHONPATH.
import importlib
mod = importlib.import_module(filepath)
Or, if you wanted to manually do the work yourself (or if you are using Python 2.6 or earlier), you can use the imp package directly:
import imp
mod = imp.load_module(imp.find_module(filename, filepath))

weird python3 import issue, No module named <module>

I write some python files like this:
main.py
view/ __init__.py #empity file
MainWindow.py
ListEditor.py
And in each file I wrote those imports:
<main.py>
from view.MainWindow import MainWindow
...
-
<MainWindow.py>
from view.ListEditor import ListEditor
and ListEditor.py don't import any files.
Each MainWindow.py or ListEditor.py defines a class that named same as the file name.
when I run the program from main.py, it works. But when I run from MainWindow.py I got ImportError: No module named 'view'
If I write
from ListEditor import ListEditor
in MainWindow.py, python MainWindow.py will be OK. but python main.py will get error:
ImportError: No module named 'ListEditor'
So, is there a way to make both python main.py and python MainWindow.py get right at the same time?
I'm using python3.4
P.S.
I think I have figured out the problem here. The import command searches a module in sys.path. The sys.path is a group of predefined paths plus the running script path. When I run the code from MainWindow.py, the code import ListEditor just works, but when I run from main.py, the current path is set to the parent path. So I need import view.ListEditor.
Well, there are couple ways to deal with it. #Vincent Beltman's answer is one of it. Or just put these code in the __init__.py file:
import os, sys
path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(path)
Finally, I'm new to python. And I think the import command is quite strange. I thought it should search the files relative to the path of the source file that containing the command, not just relative to the starter file. A starter file may varying and cause troubles like this one.
Try this:
try:
from view.ListEditor import ListEditor # If this one fails
except:
try:
from ListEditor import ListEditor # It will try this one

python unable to import module

I have my program set up using packages as followed:
-base
-init.py
-base_class.py
-test
-init.py
-test.py
When I do the import statement from base.base_class import BaseClass in the test.py I get this error when running it:
from base.base_class import BaseClass
ImportError: No module named base.base_class
How can I import this module?
at the top of test.py add
import sys
sys.path.append("..")
base is not a folder on the path...once you change this it should work
or put test.py in the same folder as base. or move base to somewhere that is on your path
you nee to have an __init__.py file in each folder you import from
You have to create a file called "__init__.py" at python directories, then "the Python" will understand that directory as a Python package.
there are 3 things you can do:
add an init.py file to each folder
add sys.path.append("Folder") to the top
or use imp and do;
import imp
foo = imp.load_source('filename', 'File\Directory\filename.py')
then foo will be the name of the module for example foo.method()

Categories

Resources