2

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?

5
  • you can use import Commented Nov 24, 2018 at 10:35
  • Thats for modules, or does it also work with scripts? Commented Nov 24, 2018 at 10:35
  • modules are just fancy scripts. import xy runs all code in xy.py, including but not limited to: creating methods, creating variables, method calls, etc Commented Nov 24, 2018 at 10:37
  • so I have to use for example: import test_script Commented Nov 24, 2018 at 10:38
  • 1
    aw, arbazz was faster than me with answering :p Commented Nov 24, 2018 at 10:38

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

If I want to make a database connection in an include, I get the error: if not self._cnx: ReferenceError: weakly-referenced object no longer exists
What type of the database do you have? And how do you create this connection? Normally you create connection in the main script, via methods provided with other imported modules and scripts.
0

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

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