import a python module whose location is unknown
Question: I would like to import a function (function.py) from a given module in python
(MOD.py), whose location I do not know. For it, I have performed two steps:

First step, I get the path to the directory that contains the module:

    
    
    path = subprocess.check_output(['find', 'home/scripts','-iname','MOD.py','|','sed','s/\/MOD.py//g']).rstrip()
    

Secondly, I point at this directory to get the function from the module:

    
    
    sys.path.insert(0,'{0}'.format(path))
    from MOD import function
    

The code written is failing in the first step, particularly in the sed. Why is
it not working? Is there a clearer way to do the first step? Is it necessary
to do two steps, or is it possible to do it with one python instruction?

Thanks!


Answer: First note that you could not use pipe like that ! for using `pipe` you have
to pass `shell=True` so instead of `check_output` use `Popen`, also your code
failed in `path` argument of `find` add a `/` before home .

If the executed command returns a nonzero exit code, an exception is raised.
you can use a `try-except` with `subprocess.CalledProcessError` to catch
errors and getting the output created along with the exit code :

    
    
    import subprocess
    
    try:
        ps = subprocess.Popen(['find', '/home/scripts','-iname','MOD.py','|','sed','s/\/MOD.py//g'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        path= ps.communicate()[0]
    except subprocess.CalledProcessError as e:
         out_bytes = e.output
         code= e.returncode
    

in addition as a more secure method i suggest don't use `shell=True` instead
use tow command :

    
    
    ps = subprocess.Popen(['find', '/home/scripts','-iname','MOD.py'], stdout=subprocess.PIPE)
    path = subprocess.check_output(['sed','s/\/MOD.py//g'], stdin=ps.stdout)
    

