Python Forum
importing libraries - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: importing libraries (/thread-4149.html)



importing libraries - u18sc11 - Jul-26-2017

I am trying to import libraries with .py extension by creating the following:
import osfiles = os.popen('dir *.py')fileit = iter(files)for file in files:        print(file) 
From this i get the following:
 sh: dir: command not found

Any help would be great, cheers.

Sandy


RE: importing libraries - sparkz_alot - Jul-26-2017

You need to post your code, output and errors between their respective tags. Refer to the Help Document on how to properly post a question. Otherwise people have to guess what you're trying to do, or not respond at all.

I am guessing that by this:
import osfiles = os.popen('dir *.py')fileit = iter(files)for file in files:        print(file) 
you actually mean this:
import os

files = os.popen('dir *.py')
fileit = iter(files)
for file in files:
    print(file) 



RE: importing libraries - DeaD_EyE - Jul-26-2017

You should use the module glob for this task: https://docs.python.org/3/library/glob.html
Or just use pathlib: https://docs.python.org/3/library/pathlib.html
And for importing, importlib: https://docs.python.org/3/library/importlib.html


I guess you want to have something like a plugin directory and your script should load them dynamically.
But this is only the half work. Somewhere you've to register this loaded plugins, to announce them in your
main program.


import glob
import importlib
import pathlib

# without pathlib
# using module glob
plugindirectory = 'plugins'
loaded_plugin_modules = []
for file in glob.glob1(plugindirectory, '*.py'):
    stem, suffix = file.rsplit('.', 1)
    to_import = 'plugins.{}'.format(stem)
    print('Importing:', to_import)
    module = importlib.import_module(to_import)
    loaded_plugin_modules.append(module)

print(loaded_plugin_modules)


# with pathlib
print('Using pathlib.Path')
plugindirectory = pathlib.Path('plugins')
loaded_plugin_modules = []
for file in plugindirectory.glob('*.py'):
    to_import = 'plugins.{}'.format(file.stem)
    print('Importing:', to_import)
    module = importlib.import_module(to_import)
    loaded_plugin_modules.append(module)

print(loaded_plugin_modules)

Instead of using stem, suffix = file.rsplit('.', 1), you can use also stem, suffix = os.path.splitext(file)


RE: importing libraries - nilamo - Jul-26-2017

(Jul-26-2017, 11:23 AM)u18sc11 Wrote: From this i get the following:
 sh: dir: command not found

dir is a windows thing. sh is not a windows thing. If you're mixing environments, then you should use libraries that are made to be platform independent, like the glob module (import glob, then glob.glob("*.py")).