Python - ModuleNotFound error using Anaconda - python

I am trying to run this program:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from io import open
from multiprocessing import Pool
import buildingspy.simulate.Simulator as si
# Function to set common parameters and to run the simulation
def simulateCase(s):
''' Set common parameters and run a simulation.
:param s: A simulator object.
'''
s.setStopTime(86400)
# Kill the process if it does not finish in 1 minute
s.setTimeOut(60)
s.showProgressBar(False)
s.printModelAndTime()
s.simulate()
def main():
''' Main method that configures and runs all simulations
'''
import shutil
# Build list of cases to run
li = []
# First model
model = 'Buildings.Controls.Continuous.Examples.PIDHysteresis'
s = si.Simulator(model, 'dymola', 'case1')
s.addParameters({'con.eOn': 0.1})
li.append(s)
# second model
s = si.Simulator(model, 'dymola', 'case2')
s.addParameters({'con.eOn': 1})
li.append(s)
# Run all cases in parallel
po = Pool()
po.map(simulateCase, li)
# Clean up
shutil.rmtree('case1')
shutil.rmtree('case2')
# Main function
if __name__ == '__main__':
main()
and I keep getting this error:
File "C:/Users/Toshiba/.spyder-py3/temp.py", line 11, in <module>
import buildingspy.simulate.Simulator as si
ModuleNotFoundError: No module named 'buildingspy'
I already installed the package using pip more than one time and nothing changes.
What am I missing?
This is the source of this code.

That error might be due to having multiple python installations on your computer:
https://docs.python.org/3/installing/#work-with-multiple-versions-of-python-installed-in-parallel
Please add the following lines somewhere to your script (or to a new script) and run it once from Spyder, and once from the console and compare the output:
import sys
print("python: {}".format(sys.version))
# also add the following if running from python 3
from shutil import which
print(which("python"))
Buildingspy has to be installed using pip, I would recommend to install it using the command:
python -m pip install -U https://github.com/lbl-srg/BuildingsPy/archive/master.zip
Anaconda adds an Anaconda prompt to the Start menu, use that to make sure the path to python.exe is correct.
Once BuildingsPy is installed correctly, you will run into the problem that on Windows multiprocessing will not work from Spyder (or, from IPython/Jupyter), please also read this issue:
https://github.com/lbl-srg/BuildingsPy/issues/179
You will have to run your script from the command line.

Related

Backward compatibility with Modernize (Python2 to Python3) fails

I have a simple sample script written in python2. Since we are migrating to python3, I am trying to get familiar with the tools that ae present. The modernize tool, helps me to achieve a python3 code. I run it, I get the result expected.
However, modernize promises backward compatibility, I expect the newly generated code to run in python2 as well.
While running with python2 Interpreter, I face issues as shown below:
Eg:
Sample.py
import Queue
from urllib2 import urlopen
def greet(name):
print 'Hello',
print name
print "What's your name?",
name = raw_input()
greet(name)
From the directory on the commandline
python-modernize -w Sample.py
New Sample.py:
from __future__ import absolute_import
from __future__ import print_function
import six.moves.queue
from six.moves.urllib.request import urlopen
from six.moves import input
def greet(name):
print('Hello', end=' ')
print(name)
print("What's your name?", end=' ')
name = input()
greet(name)
I run the new script from the command line. Produces correct results.
py Sample.py
However, since it is backward compatible, when I do the following I get errors:
C:\Python27\python.exe Sample.py
Traceback (most recent call last):
File "Sample.py", line 3, in <module>
import six.moves.queue
ImportError: No module named six.moves.queue
Should the new script be modified again? Is modernize not fully backward compatible?
Please let me know
Did you install the six module ?
pip install six
https://pypi.org/project/six/
The answer for this is on the same regard as pip installing libraries in different versions. I was installing the library in python3. So now I managed to get it done on python2. Refer here
PythonDocumentation

Import python from different folder without using .py extension

Import python from different folder without using .py extension
Below is my python script (feed_prg) that calls the python script (distribute)
Please note that my script are at different location
feed_prg is at location /opt/callscript
#!/usr/bin/env python
import sys
sys.dont_write_bytecode = True
sys.path.append('/home/username')
import distribute
# Main method start execution
def main(argv):
something = 'some'
distribute.feed(something)
if __name__ == "__main__":
main(sys.argv[1:])
distribute is at location /home/username
#!/usr/bin/env python
import sys
def feed(something):
print something
def main():
something= "some"
feed(something)
if __name__ == "__main__":
main()
I am seeing the below error while executing ./feed_prg , and only when my distribute filename is just distribute and not distribute.py
Traceback (most recent call last):
File "./feed_prg", line XX, in <module>
import distribute
ImportError: No module named distribute
the distribute also has the execute privilege, as below
-rwxr-xr-x 1 username username 3028 Dec 16 21:05 distribute
How can I fix this. ? Any inputs will be helpful
Thanks !
It is not possible to do this using import directly. It's best to simply rename the file to .py
That being said, it's possible to load the module into a variable using importlib or imp depending on your Python version.
Given the following file at path ./distribute (relative to where python is run):
# distribute
print("Imported!")
a_var = 5
Python 2
# python2import
from imp import load_source
distribute = load_source("distribute", "./distribute")
print(distribute.a_var)
Usage:
$ python python2import
Imported!
5
Python 3
#python3import
from importlib.machinery import SourceFileLoader
distribute = SourceFileLoader("distribute", "./distribute").load_module()
print(distribute.a_var)
Usage:
$ python3 python3import
Imported!
5

Error with sys.path.append and module

I am a newbie with Python and I always run scripts with terminal. Now I would like to run and debug using PyCharm. I have this script:
# -*- coding: utf-8 -*-
matplotlib.use('Agg')
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import os
import math
import time
from time import sleep
import fpformat
sys.path.append("/Users/myname/OneDrive - UCL/my_folder/build")
from my_module_name import example
When I run the script with terminal everything works.
When I use PyCharm I have this:
/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 "/Users/myname/OneDrive - UCL/my_folder/Simulations/S16/03/04_Command_compacity/8.Compact_resistance.py"
Fatal Python error: PyThreadState_Get: no current thread
The problem is here:
sys.path.append("/Users/myname/OneDrive - UCL/my_folder/build")
from my_module_name import example
I have to use this module for my master thesis and if I remove these two lines I can run other scripts, but I can't run scripts that use this module.
Could you help me? Thank you!
I typed
which python
in terminal and I changed the directory in the Python Interpreter settings

scripting python install library with pip on virtualenv

I'd like to use virtualenv in order to setup my environment and to install specific libraries.
I want to script the whole process, but so far, it's not working.
Here is my attempt:
import subprocess
import pip
virtualenv_dir="my_directory"
subprocess.call(["virtualenv", virtualenv_dir, "--system-site-packages"])
activate_this_file="{}/bin/activate_this.py".format(virtualenv_dir)
# instead of sourcing the /bin/activate file, I update dynamically
# my current python environment
execfile(activate_this_file, dict(__file__ = activate_this_file))
pip.main(["install","my_lib"])
This way, my_lib is installed on /usr/lib/python2.7/site-packages instead of "my_directory/lib/python2.7/site-packages", as I wish.
I've came up with the following work-around:
# In main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess, os
virtualenv_dir="my_directory"
subprocess.call(["virtualenv", virtualenv_dir, "--system-site-packages"])
subprocess.call([os.path.join(virtualenv_dir, 'bin/python'),"-c","import pip; pip.main(['install','my_lib'])])

How/where does Python look for modules?

I am completely new to Python and wanted to use py2neo and tornado module.
In order to do that I ran setup.py for both modules and placed them into folders
C:\Python32\modules\py2neo
and
C:\Python32\modules\tornado
In the main program I guess these lines tell the interpreter where to look for files:
import sys
sys.path.append(r'C:\Python32\modules')
# Import Neo4j modules
from py2neo import neo4j, cypher
Reading the book I also added environmental variable (in Windows 7)
PYTHONPATH = C:\Python32\modules;C:\Python32\modules\tornado;C:\Python32\modules\py2neo
Edit
Now I figured out that Python Shell has to be restarted in order to load modified PYTHONPATH variable
In case the variable value is PYTHONPATH = C:\Python32\modules
and the program contains the line
from py2neo import neo4j, cypher
then the following lines are useless:
import sys
sys.path.append(r'C:\Python32\modules')
When I run the program however I get the following error:
Traceback (most recent call last):
File "C:\...\Python Projects\HelloPython\HelloPython\Hellopy2neo.py", line 15, in <module>
from py2neo import neo4j, cypher
File "C:\Python32\modules\py2neo\neo4j.py", line 38, in <module>
import rest, batch, cypher
ImportError: No module named rest
In the file neo4j.py there are the following lines:
try:
import json
except ImportError:
import simplejson as json
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
try:
from . import rest, batch, cypher
except ImportError:
import rest, batch, cypher #line38
and rest.py file is located in folder C:\Python32\modules\py2neo so I don't know why I get the error
ImportError: No module named rest
Edit2:
Trying to import the py2neo directoy in Python Shell and list modules I get:
>>> import py2neo
>>> [name for name in dir(py2neo) if name[0] != '_']
['rest']
I guess there are some unneccesary imports as well and would be very thankful if anyone explained, which imports should be added and excluded (in PYTHONPATH and scripts) in order the program to run without errors.
I suspect the problem is that the import syntax for relative imports has changed in transition from Python 2 to Python 3:
The only acceptable syntax for relative imports is from .[module]
import name. All import forms not starting with . are interpreted as
absolute imports.
The modules you installed use the syntax that would work in Python 2. You could either install them for Python 2, or look for a version of py2neo that supports Python 3, or try to port it manually (the import line should look like from . import rest, but you'll probably face other problems later) or with 2to3 tool.
Update: I tried installing py2neo with pip. It failed for Python3 and finished successfully for Python 2. The version is 1.2.14.

Categories

Resources