I'm working through Learn Python the Hard way, and I'm currently on exercise 46 where you learn to create packages. I've created a basic package that does a few calculations, and uses a few different modules.
I've gotten the package to install in my python2.7 site packages, but I can't seem to run the module from my site packages after the fact. I'm wondering if the path that python is searching is different, because of the following:
After the install, I see this message Copying story-0.1-py2.7.egg to /usr/local/lib/python2.7/site-packages
However, when I try to run the module, I see this message /usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'story.py': [Errno 2] No such file or directory
Sorry if this makes absolutely no sense, I'm very new to the fantastical world of programing.
When you install a package, you access the internals differently. You can no longer just call python story.py.
To access the functions in story.py you need to import the module at the top of another python file, or in the interpreter.
If story.py contained
def my_test_function(blah):
print blah
You would use this function in another file by the following (after installing the module, as you've already done)
import story
story.my_test_function("Hello!")
By importing the module, you get access to all the functions and classes inside it by typing module_name.function_name. You could also just import the function you wanted to use directly, which would look something like
from story import my_test_function
my_test_function("Hello!")
Related
I'm trying to set up a roguelike Python project, but I can't seem to be able to import libtcod module into my project. This helloworld crashes, and the IDE keeps telling me that there is no module named libtcodpy.
import libtcodpy
def main():
print('Hello World!')
if __name__ == '__main__':
main()
What is the proper way to import modules into Python projects? I'm used to Java, so I was expecting something along the lines of Maven to manage the dependencies. There indeed seems to be something like that in PyCharm as well, this package manager for the venv, which from what I gather serves to isolate the project-specific stuff from the OS- or python-global stuff:
but libtcod simply isn't present in the rather exhaustive list of modules that appears after clicking on the "+" button, just some other module that has something to do with libtcod library (I guess?). Moreover, all the tutorials I found on setting libtcod up advise one to manually copy over files somewhere or run some command that I suppose does the importing somehow and other such solutions, all of which i tried and none of which worked. I don't want to pollute my project structure by using such hodgepodge ways of handling dependencies if I can at all avoid it.
Q: How do I get libtcod to work in my PyCharm project in the most clean and convention-abiding way possible?
Take a look at this github project called tcod: https://github.com/libtcod/python-tcod/blob/master/README.rst#installation
It's a python port of libtcod.
To install using pip, use the following command:
python -m pip install tcod
If you get the error "ImportError: DLL load failed: The specified module could not be found." when trying to import tcod/tdl then you may need the latest Microsoft Visual C runtime.
Blockquote
I am testing my own package, but I am struggling to import it. My package file structure is as follows:
(You can also alternatively view my Github repository here)
In PyAdventures is my init.py with the content of
name="pyadventures"
So my question is, when I import it in another python file, how come it doesn't work?
I run:
import pyadventures
But I get the following error:
No module named pyadventures
It'd be great if you could answer my question!
It's important to note that the package is in my Python package directory, not the test one I showed
New discovery! In my PyAdventures folder (the one Python actually uses) the folder only has a few files, not the ones in the screenshot above.
You can install this with pip install pyadventures
Ah, like others remark in comments and answer: The camelcase might be the problem. (Why not name it just all in lower case: pyadventures? - Else users will be as confused as its developer now :D .)
Before, I thought, it might be a problem that you want to use your module without having installed it (locally). And my following answer is for this case (using a not installed package from a local folder):
In the docs you can read:
The variable sys.path is a list of strings that determines the
interpreter’s search path for modules. It is initialized to a default
path taken from the environment variable PYTHONPATH, or from a
built-in default if PYTHONPATH is not set. You can modify it using
standard list operations:
import sys
sys.path.append('/ufs/guido/lib/python')
thus, before import do:
import sys
sys.path.append('/absolute/or/relative/path/to/your/module/pyadventures')
# Now, your module is "visible" for the module loader
import pyadventures
Alternatively, you could just place your pyadventures module folder locally in your working directory where you start python and then just do
import pyadventures
However, it is much easier to manage to keep only one version in one place and refer to this from other places/scripts. (Else you have multiple copies, and have difficulties to track changes on the multiple copies).
As far as I know, your __init__.py doesn't need to contain anything. It works if it is empty. It is there just to mark your directory as a module.
Simple. Even though the package listed on pip is namd pyadventures, in your code the directory is called PyAdventures. So that's what python knows it as. I ran import PyAdventures and it worked fine.
I am following the tutorial here:
http://www.prokopyshen.com/create-custom-zipline-data-bundle
and trying to set up a custom bundle to get price from custom, non US financial assets. I am stuck on the line that says:
Advise zipline of our bundle by registering it via .zipline/extension.py
My extension.py file is located in the .zipline/ directiory and has the following code:
from zipline.data.bundles import register
from zipline.data.bundles.viacsv import viacsv
eqSym = {
"CBA"
}
register(
'CBA.csv', # name this whatever you like
viacsv(eqSym),
)
I don't get what it means to register the bundle via .zipline/extension.py though? I thought it might mean to just run the extension.py file from my terminal via a:
python extenion.py
but that fails and says:
ImportError: No module named viacsv
How do i register this bundle?
I also followed this tutorial and I must confess this part is a little confusing.
First of all, I don't think it's necessary to run:
$ python extension.py
The error message you get probably comes from the fact that Python cannot find the viacsv.py file in sys.path (the places where it looks for modules, etc.). In the tutorial you mentioned, it's not really clear what to do with this file. As far as I am concerned, I just saved the viacsv.py file in my local site-packages directory. As I am on Linux I put it there ~/.local/lib/python2.7/site-packages but it might different for you. You can run the following python script to find out:
import sys
for dr in sys.path:
print dr
Then I just substituted from zipline.data.bundles.viacsv import viacsv with from viacsv import viacsv in extension.py.
I suspect you might be looking for the wrong place for the extension.py file.
For windows machine, the file is under "~\.zipline\extension.py". In my case, it's under "C:\Users\XXXX\.zipline\extension.py".
I had been looking at zipline folder under conda's site-packages folder, and couldn't find it. Then created an extension.py myself wondering why it's not called.
Check a related post here https://www.quantopian.com/posts/zipline-issue-while-creating-custom-bundle-to-bring-yahoo-data.
Same issue here, #Gillu13 pointed me to this solution.
I installed zipline through conda. So zipline is installed in
home/me/anaconda3/envs/krakenex/lib/python3.6/site-packages
in there you will find zipline/data/bundles and you can put viacsv.py in there...
then
from zipline.data.bundles.viacsv import viacsv
works
This is the first time I have attempted to use anything other than what's provided by python.
I have recently gotten into pythons provided Tkinter, though due to some issues I decided to use another GUI, and heard that PyQt was highly recommended, so I downloaded that and looked into various tutorials. In these tutorials, I cannot seem to execute any of the import statements in said tutorials that relate to PyQt, primarily PyQt5 (I have checked I have the correct version number by the way).
So for instance:
import PyQt5
raises the error:
Traceback (most recent call last):
File "/Users/MEBO/PycharmProjects/Music/testing.py", line 1, in <module>
import Qt
ImportError: No module named 'Qt'
[Finished in 0.1s with exit code 1]
I have a lot of research into this. I've heard people talk of using pip to install modules, and I have done this be safe (as well as downloading it from the internet), I've tried changing the project interpreter to versions Python3/ 2.7/ 2.6, appending the path name to the sys.path directory, (which I really know nothing about to be honest, I was hoping I'd get lucky), though nothing seems to work.
Are you supposed to be able to just import a module off the bat, or do you have to set some things up first?
For windows download the package and extract it to (path where python installed)\Python27\Lib and then try to import.
Specific to PyQt
This package cannot just be downloaded and imported, it must be built because it is not pure python, it uses Qt (C++) and requires dependancies. Read this tutorial on installation.
There is also a very complete python package distribution, Anaconda, that includes pyqt and much more. Almost all the packages I ever looked at are in there.
In general to pure python code
In other cases, if you place modules/code that has been download into the directory that your python script is run from, you can import off the bat, or you can append/insert any folder to the sys.path.
# importer will search here last
sys.path.append('/path/to/code/')
# importer will search here second, right after script's directory
# this can be useful to override a module temporarily...
sys.path.insert(1,'/path/to/code/')
I'm trying to run a Python program, which uses the pygame modules, from MATLAB. I know I can use either
system('python program.py')
or just
! python program.py
However, I keep getting the error:
Traceback (most recent call last):
File "program.py", line 1, in <module>
import pygame
ImportError: No module named pygame
What is strange is that if I run the program from the command line, it works just fine. Does anyone know why if run from within MATLAB, Python can't find pygame?
The problem may be that MATLAB is not seeing your PYTHONPATH, which normally stores Python libraries and modules. For custom modules, PYTHONPATH should also include the path to your custom folders.
You can try setting the value of PYTHONPATH from within a MATLAB running session:
PATH_PYTHON = '<python_lib_folder>'
setenv('PYTHONPATH', PATH_PYTHON); % set env path (PYTHONPATH) for this session
system('python program.py');
See also the possibly relevant SO answer here: How can I call a Qtproject from matlab?
As I haven't used matlab too often and don't have the program available now I cannot say for sure, but matlab may be creating a custom environment with custom paths (this happens a lot, so the user has a very consistent experience in their software). When matlab installs it may not export paths to its own modules to your default environment. So when calling for pygame.py outside of matlab, python cannot find pygame.py under its usual lookup paths.
Solutions could be:
find the pygame.py, and map the path to it directly in your code, though this could cause you headaches later on during deployment
Try just copying the pygame.py file to your working directory, could have dependences that need to addressed.
Install pygame directly from its developer at http://www.pygame.org. Version differences could be a problem but pygame gets put under the usual lookup paths for python. (This would be my preferred solution personally.)
Or just export the location of path to pygame in matlab's library to your default enivronment. This could be a problem during deployment too.
For posterity, first try everything that Stewie noted here ("Undefined variable "py" or class" when trying to load Python from MATLAB R2014b?). If it doesnt work then it's possible that you have multiple pythons. You can try and check which python works (with all the related installed modules) on your bash/terminal. And then use
pyversion PYTHONPATH
to let matlab know the right path.
Also use py.importlib.import_module('yourmodule') to import the module after that.
That should get you started.