'Python - Include another Python script

I have a question. When you are programming in PHP you can use this to include external php script to current script.

include('test_page.php');

So you don't have to repeat a code in every script. Is there a way in Python to include another Python script, just like the php page?



Solution 1:[1]

In Python,

you can import the different scripts/modules by using import , just make sure they are in same directory and proper function/class.

If modulename.py is an function

import modulename

if modulename.py is a set a different functions.

from modulename import particularfunction

Solution 2:[2]

If you have "script.py", just make:

import script

If you have a particular function or a class in the script then:

from script import function

Remember having it in the pwd. If the script is not in pwd, then you need to append a path to it. So before importing:

import sys
sys.path.append("PATH_TO_SCRIPT")

import script

Solution 3:[3]

If you are trying to reuse code, or a code fragment, import does not work, because it treats the code as a component of whatever package it is stored with. import is good for subroutines/method addressability, not much else

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arbazz Hussain
Solution 2 artona
Solution 3 virgil