简体   繁体   中英

Python - how do i load my custom class methods from a root directory?

How do import my class from a specific directory (in my case root directory i want to keep it).

So, i have following directory map, now i need to load the class parsePresets from myglobal.py file, which is located in root directory: /var/tmp/mypython directory.

but, i want to import that from class/methods from my new module: /var/tmp/mypython/media/test.py with:

from myglobal import parsePresets

but i am getting:

    from myglobal import parsePresets
ImportError: No module named myglobal

i also have init .py in root directory and in the media directory.

$ cd /var/tmp/mypython; tree
.
├── arduino
│   ├── arduino.diest.c
│   ├── arduino.gent.c
│   ├── arduino.lalouvier.c
│   ├── arduino.makenoise.c
│   ├── arduino.servo.c
│   ├── arduino.string.c
│   ├── arduino.tcpserver.c
│   ├── arduino.tcpserver.c~
│   ├── arduino.test.sh
├── bash
│   ├── all.sh
│   ├── alsa-info.sh
│   ├── asound.conf
│   ├── autoreboot.sh
│   ├── diskfix.sh
│   ├── kernelfix.sh
│   ├── update.sh
│   └── usbformat.sh
├── chrome.py
├── download.py
├── download.sh
├── gui.py
├── image
│   ├── a.png
│   ├── b.gif
│   ├── cross_new.png
│   ├── e150
│   │   ├── 1.png
│   │   ├── de.png
│   │   ├── en.png
│   │   ├── __init__.py
│   │   └── nl.png
│   ├── __init__.py
│   ├── logo.png
│   ├── menu.jpg
│   └── slider_btn.png
├── __init__.py
├── INSTALL
├── ip.py
├── loading.py
├── logout.py
├── media
│   ├── __init__.py
│   ├── test.py
├── menu.py
├── myglass.py
├── myglass.pyc
├── myglobal.py
├── myglobal.pyc
├── rightclick.py
├── runme.sh
├── server.py
├── server.pyc
├── src.nja
├── test
│   ├── Button.py
│   ├── json.py
│   ├── json.pyc
│   ├── keyboard.py
│   ├── loop.sh
│   ├── mytimer.py
│   ├── qtclick.py
│   ├── qtmouse.py
│   ├── qt.py
│   ├── qtwindows7.py
│   ├── shape.py
│   ├── skeleton.py
│   ├── slider.py
│   ├── testpreview.py
│   ├── test.py
│   ├── Text.py
│   ├── transparent.py
│   ├── transparentwindow.py
│   └── Vscale.py
├── test.py
├── unavailable.py
├── upload.sh
└── internet
    ├── backup
    ├── protocol.txt    
    └── server.py

You can add sys.path.append(/var/tmp/mypython/media/) to your script.

EDIT:

$ cat >> /var/tmp/mypython/stackoverflow.py <<\EOF
import sys
sys.path.append("/var/tmp/mypython/")
from myglobal import parsePresets
EOF
$ python /var/tmp/mypython/stackoverflow.py

or with NINJA-IDE

Running: /var/tmp/mypython/media/stackoverflow.py (Wed Dec 11 13:37:25 2013)



Execution Successful!

Use relative imports

from ..myglobal import parsePresets

The extra periods . take you "out" a level in your hierarchy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM