I tried importing without the .py file extension ex: import something. That doesen't work. I also tried turning it into a package by creating a init.py but it still doesn't want to import. Oh and by the way I'm using Python 3.5 . Edit: I'm using pythonista and at the moment do not have access to a computer and/or Xcode.
Asked
Active
Viewed 3,586 times
2 Answers
1
In pythonista the Documents folder is not in sys.path by default. The site-packages folder is, or the path of the current script you are running. If you try to import foo
from the console, this will fail unless the path that contains foo.py is on sys.path.
You have three basic options: 1) put your "libraries" into site-packages (found from Modules & Templates, but really the path is ~/Documents/site-packages)
2) Specifically add the path before import, such as if you have foo.py inside Documents/somefolder
sys.path.append(os.expanduser('~/Documents/somefolder'))
import foo
(though you should first check if the path is in sys.path so you don't get duplicates)
3) Use impprtlib.find_module

JonB
- 350
- 1
- 7
0
I didn't know you could do this on iOS but I found a fix from another user. This code is not mine but it is sorin's.
import os, sys, inspect
# realpath() will make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# use this if you want to include modules from a subfolder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
# Info:
# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
# __file__ fails if script is called in different ways on Windows
# __file__ fails if someone does os.chdir() before
# sys.argv[0] also fails because it doesn't not always contains the path