30

I'm trying to import a python file to my application which is written in python.

I have the following code:

import os
from os.path import basename

class specificClass:
    def dothing(self,path):
          runcommand = __import__("/root/"+ os.path.splitext(os.path.basename(path))[0]+ "/" + os.path.splitext(os.path.basename(path))[0] +"/sa/update.py")
          runcommand.main()

When I run it, it gives me the following error:

ImportError: Import by filename is not supported.
salmanwahed
  • 9,450
  • 7
  • 32
  • 55
Or Smith
  • 3,556
  • 13
  • 42
  • 69
  • This error is also raised when trying to add a route in pyramid and you don't put the normal route path as 2nd parameter. Example: config.add_route('admin_ajax_get_items', 'admin_ajax_get_items') instead of config.add_route('admin_ajax_get_items', '/url/path') – Dragos Rusu Nov 13 '15 at 14:48

1 Answers1

12

Instead of doing a import like __import__ you can say

import sys
sys.path.append(path) # this is where your python file exists
import update
hyades
  • 3,110
  • 1
  • 17
  • 36
  • does that mean I am forced to add to path the folder where the package functions that I want to run are located at? Say that there is one function I want to run in `..`, is there a way to import that function in **any** way? – Charlie Parker Jun 22 '16 at 06:39
  • 11
    Doesn't actually answer the question, and generally promotes an extremely bad practice of modifying your system path within python modules. – Slater Victoroff Apr 13 '17 at 16:41
  • 13
    What is the correct way of doing this? – Sajuuk Aug 09 '17 at 06:28