IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

aide Fonction __Import__ [Python 2.X]


Sujet :

Python

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Homme Profil pro
    Supinfo
    Inscrit en
    Février 2013
    Messages
    12
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Supinfo
    Secteur : Industrie

    Informations forums :
    Inscription : Février 2013
    Messages : 12
    Par défaut aide Fonction __Import__
    Bonjour, afin de terminer mon projet j'ai besoin d'utiliser la librairie Inspect mais pour cela j'ai besoin d'importer different module qui ce trouve dans d'autre script (qui ne sont pas de moi), si quel qu'un pourrait regarder si j'utilise bien __Import__ car pour pas vous mentir je suis totalment perdu la dessus ... Je vous remercie d'avance.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    for file in allfiles:
                try:
                    name = os.path.splitext(os.path.basename(file))[0]
                    backends[name] = __import__('BINoculars.backends.{0}'.format(name), globals(), locals(), [], -1)
                except ImportError as e:
                    print 'Import backend error: {0} with error message {1}'.format(name, e.message)
            print inspect.getmembers(backends['id03'])

  2. #2
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 716
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 716
    Par défaut
    Salut,

    Citation Envoyé par Myrens Voir le message
    j'ai besoin d'utiliser la librairie Inspect mais pour cela j'ai besoin d'importer different module qui ce trouve dans d'autre script (qui ne sont pas de moi), si quel qu'un pourrait regarder si j'utilise bien __Import__ car pour pas vous mentir je suis totalment perdu la dessus
    Je ne vois pas le rapport entre inspect et __import__.
    Et je ne comprends pas non plus pourquoi vous n'utilisez pas simplement "import".

    Ceci dit, préciser la version de Python utilisée et le problème rencontré... aiderait un peu.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  3. #3
    Membre averti
    Homme Profil pro
    Supinfo
    Inscrit en
    Février 2013
    Messages
    12
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Supinfo
    Secteur : Industrie

    Informations forums :
    Inscription : Février 2013
    Messages : 12
    Par défaut
    Et bien en gros j'ai cree une interface graphique avec PyQt4 et Python 2.7 pour un script deja existant, et donc j'ai besoin de recuperer des ellements d'ou l'utilisation d'inspect (qui n'est pas le probleme) mais pour cela je doit importer different module qui sont dans le script(ce qui est mon probleme) pour pouvoir utiliser ces ellements. Bien entendu j'ai deja essayais avec simpliement import mais cela ne marche pas,d'ou le faite que j'utilise __Import__ .

    apres je veux bien vous montrer le message, mais il est un peu long ...
    archon:~/Downloads/binoculars-master % python main.py
    Import backend error: id03_xu with error message No module named tables
    Import backend error: bm25 with error message cannot import name config
    [('__builtins__', {'bytearray': <type 'bytearray'>, 'IndexError': <type 'exceptions.IndexError'>, 'all': <built-in function all>, 'help': Type help() for interactive help, or help(object) for help about object., 'vars': <built-in function vars>, 'SyntaxError': <type 'exceptions.SyntaxError'>, 'unicode': <type 'unicode'>, 'UnicodeDecodeError': <type 'exceptions.UnicodeDecodeError'>, 'memoryview': <type 'memoryview'>, 'isinstance': <built-in function isinstance>, 'copyright': Copyright (c) 2001-2012 Python Software Foundation.
    All Rights Reserved.

    Copyright (c) 2000 BeOpen.com.
    All Rights Reserved.

    Copyright (c) 1995-2001 Corporation for National Research Initiatives.
    All Rights Reserved.

    Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
    All Rights Reserved., 'NameError': <type 'exceptions.NameError'>, 'BytesWarning': <type 'exceptions.BytesWarning'>, 'dict': <type 'dict'>, 'input': <built-in function input>, 'oct': <built-in function oct>, 'bin': <built-in function bin>, 'SystemExit': <type 'exceptions.SystemExit'>, 'StandardError': <type 'exceptions.StandardError'>, 'format': <built-in function format>, 'repr': <built-in function repr>, 'sorted': <built-in function sorted>, 'False': False, 'RuntimeWarning': <type 'exceptions.RuntimeWarning'>, 'list': <type 'list'>, 'iter': <built-in function iter>, 'reload': <built-in function reload>, 'Warning': <type 'exceptions.Warning'>, '__package__': None, 'round': <built-in function round>, 'dir': <built-in function dir>, 'cmp': <built-in function cmp>, 'set': <type 'set'>, 'bytes': <type 'str'>, 'reduce': <built-in function reduce>, 'intern': <built-in function intern>, 'issubclass': <built-in function issubclass>, 'Ellipsis': Ellipsis, 'EOFError': <type 'exceptions.EOFError'>, 'locals': <built-in function locals>, 'BufferError': <type 'exceptions.BufferError'>, 'slice': <type 'slice'>, 'FloatingPointError': <type 'exceptions.FloatingPointError'>, 'sum': <built-in function sum>, 'getattr': <built-in function getattr>, 'abs': <built-in function abs>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'print': <built-in function print>, 'True': True, 'FutureWarning': <type 'exceptions.FutureWarning'>, 'ImportWarning': <type 'exceptions.ImportWarning'>, 'None': None, 'hash': <built-in function hash>, 'ReferenceError': <type 'exceptions.ReferenceError'>, 'len': <built-in function len>, 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development. See www.python.org for more information., 'frozenset': <type 'frozenset'>, '__name__': '__builtin__', 'ord': <built-in function ord>, 'super': <type 'super'>, 'TypeError': <type 'exceptions.TypeError'>, 'license': Type license() to see the full license text, 'KeyboardInterrupt': <type 'exceptions.KeyboardInterrupt'>, 'UserWarning': <type 'exceptions.UserWarning'>, 'filter': <built-in function filter>, 'range': <built-in function range>, 'staticmethod': <type 'staticmethod'>, 'SystemError': <type 'exceptions.SystemError'>, 'BaseException': <type 'exceptions.BaseException'>, 'pow': <built-in function pow>, 'RuntimeError': <type 'exceptions.RuntimeError'>, 'float': <type 'float'>, 'MemoryError': <type 'exceptions.MemoryError'>, 'StopIteration': <type 'exceptions.StopIteration'>, 'globals': <built-in function globals>, 'divmod': <built-in function divmod>, 'enumerate': <type 'enumerate'>, 'apply': <built-in function apply>, 'LookupError': <type 'exceptions.LookupError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'basestring': <type 'basestring'>, 'UnicodeError': <type 'exceptions.UnicodeError'>, 'zip': <built-in function zip>, 'hex': <built-in function hex>, 'long': <type 'long'>, 'next': <built-in function next>, 'ImportError': <type 'exceptions.ImportError'>, 'chr': <built-in function chr>, 'xrange': <type 'xrange'>, 'type': <type 'type'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'Exception': <type 'exceptions.Exception'>, 'tuple': <type 'tuple'>, 'UnicodeTranslateError': <type 'exceptions.UnicodeTranslateError'>, 'reversed': <type 'reversed'>, 'UnicodeEncodeError': <type 'exceptions.UnicodeEncodeError'>, 'IOError': <type 'exceptions.IOError'>, 'hasattr': <built-in function hasattr>, 'delattr': <built-in function delattr>, 'setattr': <built-in function setattr>, 'raw_input': <built-in function raw_input>, 'SyntaxWarning': <type 'exceptions.SyntaxWarning'>, 'compile': <built-in function compile>, 'ArithmeticError': <type 'exceptions.ArithmeticError'>, 'str': <type 'str'>, 'property': <type 'property'>, 'GeneratorExit': <type 'exceptions.GeneratorExit'>, 'int': <type 'int'>, '__import__': <built-in function __import__>, 'KeyError': <type 'exceptions.KeyError'>, 'coerce': <built-in function coerce>, 'PendingDeprecationWarning': <type 'exceptions.PendingDeprecationWarning'>, 'file': <type 'file'>, 'EnvironmentError': <type 'exceptions.EnvironmentError'>, 'unichr': <built-in function unichr>, 'id': <built-in function id>, 'OSError': <type 'exceptions.OSError'>, 'DeprecationWarning': <type 'exceptions.DeprecationWarning'>, 'min': <built-in function min>, 'UnicodeWarning': <type 'exceptions.UnicodeWarning'>, 'execfile': <built-in function execfile>, 'any': <built-in function any>, 'complex': <type 'complex'>, 'bool': <type 'bool'>, 'ValueError': <type 'exceptions.ValueError'>, 'NotImplemented': NotImplemented, 'map': <built-in function map>, 'buffer': <type 'buffer'>, 'max': <built-in function max>, 'object': <type 'object'>, 'TabError': <type 'exceptions.TabError'>, 'callable': <built-in function callable>, 'ZeroDivisionError': <type 'exceptions.ZeroDivisionError'>, 'eval': <built-in function eval>, '__debug__': True, 'IndentationError': <type 'exceptions.IndentationError'>, 'AssertionError': <type 'exceptions.AssertionError'>, 'classmethod': <type 'classmethod'>, 'UnboundLocalError': <type 'exceptions.UnboundLocalError'>, 'NotImplementedError': <type 'exceptions.NotImplementedError'>, 'AttributeError': <type 'exceptions.AttributeError'>, 'OverflowError': <type 'exceptions.OverflowError'>}), ('__doc__', None), ('__file__', '/users/rnencib/Downloads/binoculars-master/BINoculars/__init__.pyc'), ('__name__', 'BINoculars'), ('__package__', 'BINoculars'), ('__path__', ['/users/rnencib/Downloads/binoculars-master/BINoculars']), ('backend', <module 'BINoculars.backend' from '/users/rnencib/Downloads/binoculars-master/BINoculars/backend.pyc'>), ('backends', <module 'BINoculars.backends' from '/users/rnencib/Downloads/binoculars-master/BINoculars/backends/__init__.pyc'>), ('dispatcher', <module 'BINoculars.dispatcher' from '/users/rnencib/Downloads/binoculars-master/BINoculars/dispatcher.pyc'>), ('errors', <module 'BINoculars.errors' from '/users/rnencib/Downloads/binoculars-master/BINoculars/errors.pyc'>), ('load', <function load at 0x7fccbec527d0>), ('os', <module 'os' from '/usr/lib/python2.7/os.pyc'>), ('plot', <function plot at 0x7fccbec528c0>), ('run', <function run at 0x7fccbec52758>), ('save', <function save at 0x7fccbec52848>), ('space', <module 'BINoculars.space' from '/users/rnencib/Downloads/binoculars-master/BINoculars/space.pyc'>), ('sys', <module 'sys' (built-in)>), ('transform', <function transform at 0x7fccbec52938>), ('util', <module 'BINoculars.util' from '/users/rnencib/Downloads/binoculars-master/BINoculars/util.pyc'>)]

  4. #4
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 716
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 716
    Par défaut
    Salut,

    mais pour cela je doit importer different module qui sont dans le script(ce qui est mon probleme) pour pouvoir utiliser ces ellements.
    __import__ fonctionne de la même façon qu'import... et si vous essayez de "charger" des fichiers .py sans respecter l'environnement dans lequel ils pourront être chargés çà ne fonctionnera pas.

    Ceci dit, comme je ne comprends toujours pas ce que vous faites (ni pourquoi), pas facile de vous aider.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  5. #5
    Membre averti
    Homme Profil pro
    Supinfo
    Inscrit en
    Février 2013
    Messages
    12
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Supinfo
    Secteur : Industrie

    Informations forums :
    Inscription : Février 2013
    Messages : 12
    Par défaut
    Normalement avec c'est 2 lignes de code je respecte l'arboresence de mon dossier qui contient mes fichier
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    name = os.path.splitext(os.path.basename(file))[0]
    backends[name] = __import__('BINoculars.backends.{0}'.format(name), globals(), locals(), [], -1)
    d'ou le faite que je comprennes absolument pas le probleme. Apres vous n'etes pas obligez de me vouvoyer je ne suis qu'un simple etudiant ^^

    peut etre si vous connaissez une autre autre method pour faire cela ou un exemple de __Import__ qui fonctionne cela pourra mettre utile a mieux comprendre ou a y voir plus claire

  6. #6
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 716
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 716
    Par défaut
    Citation Envoyé par Myrens Voir le message
    Normalement avec c'est 2 lignes de code je respecte l'arboresence de mon dossier qui contient mes fichier
    L'arborescence des fichiers peut être mais pas celle des "import" exécutés par le script auxquels est appliqué __import__...
    Et il manque certainement l'ajout de chemins dans sys.path (mais probablement pas que...)

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. aide fonction tri heapsort (création du tas)
    Par Invité dans le forum C
    Réponses: 6
    Dernier message: 24/11/2009, 00h27
  2. [aide fonction popup.close() ]
    Par viny dans le forum Général JavaScript
    Réponses: 6
    Dernier message: 17/07/2006, 16h41
  3. Aide fonction getopt
    Par makohsarah dans le forum C
    Réponses: 12
    Dernier message: 12/06/2006, 16h02
  4. aide fonction math[racine,cos(),sin(),..]VB6
    Par am.adnane dans le forum VB 6 et antérieur
    Réponses: 3
    Dernier message: 28/12/2005, 18h40
  5. besoin d'aide fonction avec fichier (debutant)
    Par boby61 dans le forum Débuter
    Réponses: 9
    Dernier message: 14/03/2005, 11h22

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo