Python sys path insert

How to add a Python module to syspath?

Strictly taken, a module is a single python file, while a package is a folder containing python files, accompanied by a (can be empty) file named __init__.py , to tell python it is a package to import modules from. In both cases, modules need their .py extension, but importing them is done without (see further below).

By default, Python looks for its modules and packages in $PYTHONPATH .

To find out what is included in $PYTHONPATH, run the following code in python (3):

Читайте также:  Starting with python on linux

How to add a directory

From within a python file, you can add path(s) occasionally to the default path by adding the following lines in the head section of your python application or script:

import sys sys.path.insert(0, "/path/to/your/package_or_module") 

if I have a folder: /home/myname/pythonfiles , and I want to import the file module_1.py , located in that directory, I add this to the head section of my code:

import sys sys.path.insert(0, "/home/myname/pythonfiles") 

And I can simply import the file module_1.py by:

When I create a package and want to import module(s) from the package, I need to create a folder in $PYTHONPATH , containing the modules, accompanied by a (can be empty) file called __init__.py

To import from a package (folder) called my_package in /home/myname/pythonfiles , add the /home/myname/pythonfiles path to your $PYTHONPATH , like in example 1, and import the module called module_2.py (inside the package folder) simply with: `

Adding directories to $PYTHONPATH permanently:

Add the following line to your ~/.profile file.

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add 

Subdirectories

From within a package, subdirectories are not included just like that; you need to «chain» the directories. To import a module module_3.py , inside folder subfolder inside folder packagename :

import packagename.subfolder.module_3 

Given the fact that all subfolders in the package include their own __init__.py file.

When a module is in the same directory as the script or application

There is no need to insert the path to a module when it is in the same directory as the script or application, it is automatically added.

If I have a folder, containing script.py and module.py , I can simply import the module by:

Источник

Learn How to Import from Subdirectory in Python

Let us imagine that you are going to work on a big project. On that, you need to import a module, classes, or some variables from the subdirectory to your code. Sometimes it may not work properly. Or it may throw some error . Are you struggling with that? If yes, no worries. This article is going to be very useful for you. Yes, we are going to learn about how to import from a subdirectory in python. This section will learn how to import a file, module, class, and variables from a subdirectory.

We can access a module, variables, files from a subdirectory using two different functions. __init__.py, sys.path.append() and sys.path.insert() are the methods useful to import from subdirectory. These methods are useful to reduce the lines of our code. Here we are going to implement simple programs only for the understanding purpose. So many of you can think, why are we using these methods? We can directly implement. I hope my guess is correct. These methods are useful to develop large programs. So now you got a clear idea about these methods.

Using __init__.py method

__init__.py is the best and correct method to import from subdirectories comparing among all the methods.

Steps to follow:

  • Create a subfolder and add __init__.py to the folder.
  • __init__.py file may be an empty file or it may contain some code lines
  • __init__.py method is useful to differentiate between a simple directory and a package.
  • Now you can create a file in the same folder that is where the __init__.py file is located.
  • This file contains some lines of code that have to be imported in the main program
  • Now in a main.py file, we have to import a directory name and file name.

Code in file.py(subdirectory)

def add(a,b): return a+b def sub(a,b): return a-b def product(a,b): return a*b def quotient(a,b): return a/b print("The addition of two numbers are:",add(9,4))

This code performs simple calculations. Now we will import this module in a main.py

import directoryname.filename

Code in main

The addition of two numbers are: 13

What is sys.path.insert() in python?

The sys.path.insert () is a function in a sys module. This is useful to access a module from a subdirectory. It usually takes two arguments. This is useful to specify the path of the file.

Syntax

Parameters

How to import a file from a subdirectory in python using insert()?

Consider you have two files named add.py and main.py. The add.py is the python file we are going to import from the subdirectory. This add.py file is not located in the python directory. main.py is a python file that is located in the python directory. Now we are going to import an add.py file in main.py.

Code in add.py

num1=int(input("Enter a number:")) num2=int(input("Enter a number:")) print("The addition of two number is:",num1+num2)

This is the normal addition code. This file is located in the path “E:\Python programs” on my PC. Now I am going to write a code for main.py.

Code in main.py

import sys sys.path.insert(0,"E:\Python programs") import add

Here we have imported the add.py file to the main.py file. Now we will execute the main.py file to see the result.

RESTART: C:/Users/AppData/Local/Programs/Python/Python39/main.py Enter a number:65 Enter a number:2 The addition of two number is: 67

This is the result we got output for main.py. For the confirmation, I added the output with a path.

How to import a module from a subdirectory in python using insert()?

Now we are going to import a module from a subdirectory. Consider in a program.py there is a module that has two functions add.py and sub.py. Now using main.py, we are going to import those two in our main program.

Code in program.py

def add(a,b): return a+b def sub(a,b): return a-b

This is the code we have written in the program.py file.

Code in main.py

import sys sys.path.insert(0,"E:\Python programs") from program import add,sub print("The Addition of two number is:",add(3,8)) print("The difference between two number is:",sub(9,4))

Here we have imported a program.py. We are just importing add and sub from the program—next, printing results by simply giving the inputs.

RESTART: C:/Users/AppData/Local/Programs/Python/Python39/main.py The Addition of two number is: 11 The difference between two number is: 5

How to import a class from a subdirectory using insert()?

Now let us learn how to import a class. To import a class we have to give the class name as:

from filename import classname

Code in file1.py

class value1_class: m=4 def show(value): print("Welcome!")

Now we will write a code for main.py

Code in main.py

import sys sys.path.insert(0,'E:\Python programs') from file1 import value1_class var1 = value1_class() var1.show()

How to import variables from a subdirectory in python using insert()?

Now we will move on to how to import variables from another program to our main program.

Creating some variables in value.py

string="Python Pool" string1="Latracal Solutions" a=10 b=20 c=70 d=80 e=30

Here I have given some values assigned to some variables. Now I am going to import those variables into main.py files.

Code in main.py

import sys sys.path.insert(0,"E:\Python programs") import values print("The value of a is:",values.a) print("You are learning in:",values.string)

Here I have not assigned any values for the variables. But I can get the values of the variables from the specified file.

The value of a is: 10 You are learning in: Python Pool

What is sys.path.append()?

The sys.path.append () is a function in a sys module. This is useful to access a module from a subdirectory. It takes only one argument. This is useful to specify the path of the file.

Syntax

Parameter

path: a path of the subdirectory

How to import a file from a subdirectory in python using append()?

Now we will import porduct.py from another subdirectory. product.py is a code that is to calculate the product of two numbers. main.py is a python file located in a python directory. In this, we will import a subdirectory path.

Code in product.py

num1=int(input("Enter a value of a:")) num2=int(input("Enter a value of b:")) print("The product of two number is:",num1*num2)

This is the normal multiplication code. This file is located in the path “E:\Python programs” on my PC. Now I am going to write a code for main.py.

Code in main.py

import sys sys.path.append("E:/Python Programs") import product

Here we have imported the product.py file to the main.py file. Now we will execute the main.py file to see the result.

RESTART: C:/Users/AppData/Local/Programs/Python/Python39/main.py Enter a value of a:4 Enter a value of b:5 The product of two number is: 20

How to import a module from a subdirectory using append()?

Now we are going to import a module from a subdirectory using append . Consider in a test.py there is a module that has two functions, product.py and divide.py. Now using main.py, we are going to import those two in our main program.

Code in test.py

def product(a,b): return a*b def divide(a,b): return a/b

Code in main.py

import sys sys.path.append("E:/Python Programs") from test import product,divide print("The product is:",product(3,6)) print("The quotient is:",divide(9,3))
RESTART: C:/Users/AppData/Local/Programs/Python/Python39/main.py The product is: 18 The quotient is: 3.0

How to import a class from a subdirectory using append()?

Now let us learn how to import a class.

Code in file1.py

class value1_class: n=4 def show(value): print("Python!")

Now we will write a code for main.py

Code in main.py

import sys sys.path.append('E:\Python programs') from file1 import value1_class var1 = value1_class() var1.show()

How to import variables from a subdirectory using append()?

So far, we have learned how to import files and modules from subdirectories using the append method. Now we have to go for variables.

We have already created a python value.py. This file already contains some variables, so that we can use that values in this code too.

Creating some variables in value.py

string="Python Pool" string1="Latracal Solutions" a=10 b=20 c=70 d=80 e=30

Code in main.py

import sys sys.path.append("E:\Python programs") import values print("The value of b is:",values.b) print("Python Pool is developed by:",values.string1)
The value of b is: 20 Python Pool is developed by: Latracal Solutions

The sys.path.insert() method takes two arguments.

Yes, we can use 0 as well as 1 in sys.path.insert() method.

Conclusion

So far, we have briefly learned about how to import from subdirectories in python. These methods will reduce the line of codes. This is the efficient method in python. As a programmer, it is necessary to know how to import from subdirectories. If you have any queries, do let us know in the comment box.

Источник

Оцените статью