Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I can see at least one problem with your code. The line...</p> <pre><code>if os.path.isdir(d): </code></pre> <p>...won't work, because <code>os.listdir()</code> returns relative pathnames, so you'll need to convert them to absolute pathnames, otherwise the <code>os.path.isdir()</code> will return <code>False</code> because the path doesn't exist (relative to the current working directory), rather than raising an exception (which would make more sense, IMO).</p> <p>The following code works for me...</p> <pre><code>import sys import os # Directories to search for packages root_path_list = ("/modules", "/other_modules",) # Make a backup of sys.path old_sys_path = sys.path[:] # Add all paths to sys.path first, in case one package imports from another for root_path in root_path_list: sys.path.insert(0, root_path) # Add new packages to current scope for root_path in root_path_list: filenames = os.listdir(root_path) for filename in filenames: full_path = os.path.join(root_path, filename) if os.path.isdir(full_path): locals()[filename] = __import__(filename) # Restore sys.path sys.path[:] = old_sys_path # Clean up locals del sys, os, root_path_list, old_sys_path, root_path, filenames, filename, full_path </code></pre> <hr> <p><strong>Update</strong></p> <p>Thinking about it, it might be safer to check for the presence of <code>__init__.py</code>, rather than using <code>os.path.isdir()</code> in case you have subdirectories which don't contain such a file, otherwise the <code>__import__()</code> will fail.</p> <p>So you could change the lines...</p> <pre><code> full_path = os.path.join(root_path, filename) if os.path.isdir(full_path): locals()[filename] = __import__(filename) </code></pre> <p>...to...</p> <pre><code> full_path = os.path.join(root_path, filename, '__init__.py') if os.path.exists(full_path): locals()[filename] = __import__(filename) </code></pre> <p>...but it might be unnecessary.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload