Python - Modelica connection fails due to import error - python

I am trying to connect Modelica and Python using the Python27 block, provided by the Berkeley Simulations Lab:
http://simulationresearch.lbl.gov/modelica
I use this block to call a Python function:
def Test2(WriteValues):
''' Connection Test - Works if started from Dymola
'''
#Doing nothing and returning the input
ReturnList=WriteValues
return (ReturnList)
works perfectly.
Now I need to import some modules
#Importing Python modules works in general
import sys
import thread
import time
works aswell
Only now I want to import a module that is not part of Python but a site-package:
def Test1(WriteValues):
'''Connection Test - Doesnt work if started from Dymola
'''
#Importing some Bacpypes Module
#Path is by default C:\Python27\Lib\site-packages\BACpypes-0.7-py2.7.egg\bacpypes
#My os is win7
from bacpypes.core import run
#Doing nothing and returning the input
ReturnList=WriteValues
return (ReturnList)
This does not work. It does not matter if I import the BACpypes module inside a function or globally - the error is always
'module' object has no attribute 'argv'
Colleagues pointed me to the idea that it might be related to a multiple import problem. The function is being called by Modelica every 10 seconds (real-time-simualtion).
If I call the function Test1 outside of Modelica, there is no problem. It only fails using the Python27 block!
Does anyone have an idea about how to make the BACpypes import work?
UPDATE 2013-10-16:
I printed out the value of sys.argv for the script excecution in the Python directory and an excecution from Modelica.
sys.argv from Python directory:
['C:\\Python27\\Testcon.py']
sys.argv if function is called from inside Modelica:
['modpython']
Might this in any way be related to the error message I get?

The bug is caused because bacpypes uses sys.argv but the Python interpreter did not call PySys_SetArgv.
This will be fixed in the next version of the Modelica Buildings library, see https://github.com/lbl-srg/modelica-buildings/issues/191

Related

Python Module not found error - not getting fixed

So I am pretty new with Python. I've been working on running with a code similar to one I hope to build myself (so a reference code). Aside from some bugs I need to work out with invalid syntax, all seems to work except for one issue with one particular .py file I have.
My structure is this:
MoodForecasting -> eval -> nsga_two.py
I do have _init_.py in eval folder though, so I'm not sure why this block of code isn't working.
I am trying to load one particular fucntion from it, so the structure should look like this
from nsga_two import PatientProblem
Unfortunately, I keep getting the error ModuleNotFoundError: No module named 'nsga_two'.
I checked nsga_two.py itself and found that it couldn't load inspyred. I went in and was able to fix this. So, nsga_two.py runs fine on its own. However, I cannot import it into the main script I will be working with.
Some extra details: I am working with the IDE Spyder with Python Custom Version 3.7.9.
I'm not sure if it is an issue with Spyder or just how I am loading in my working directory. (Most of my coding experience is in MatLab and R so having an IDE similar to RStudio and MatLab is the reason I chose to work in Spyder)
Edit:
I got a syntax error when using from eval import nsga_two.PatientProblem. Python didn't like the period. So, I instead tried it with no period. I got the error cannot import name 'nsga_twoPatientProblem' from 'eval' (C:\Users\name\Desktop\MoodForecasting-master\MoodForecasting-master\eval\__init__.py). I don't know why. But doing from eval import nsga_two works. nsga_two.py only consists of PatientProblem. This solve should be ok for this purpose. I'm just not sure why this could be happening.
Suppose your structure is like:
MoodForecasting-master/
main.py
eval/
__init__.py
nsga_two.py
When you run the main script to import something, the directory of that script is added to the module search path sys.path, .../MoodForecasting-master/ in this case. from nsga_two import PatientProblem raised ModuleNotFoundError because nsga_two.py is not in that directory.
As Iguananaut said, from eval import nsga_two.PatientProblem in the first comment has never been a valid statement. The valid ways of doing so are:
import by from eval import nsga_two and use as nsga_two.PatientProblem().
import by from eval.nsga_two import PatientProblem and use as PatientProblem() directly.
Module search starts from .../MoodForecasting-master/, first option go to .../MoodForecasting-master/eval/ to find nsga_two.py, second option go to .../MoodForecasting-master/eval/nsga.py to find attribute named PatientProblem.
The correct syntax would be:
from package.module import function
so:
from eval.nsga_two import PatientProblem

Run python script from another python script on linux

I'm using python 2.7 and ubuntu 16.04.
I have a simple REST server on python: file server_run.py in module1 which is importing some scripts from module2.
Now I'm writing an integration test, which is sending POST request to my server and verify that necessary action was taken by my server. Obviously, server should be up and running but I don't want to do it manually, I want to start my server (server_run.py which has also main method) from my test: server_run_test.py file in module3.
So, the task sounds very simple: I need to start one python script from another one, but I spent almost the whole day. I found a couple of solutions here, including:
script_path = "[PATH_TO_MODULE1]/server_run.py"
subprocess.Popen(['python', script_path], cwd=os.path.dirname(script_path))
But my server is not coming up, throwing the error:
Traceback (most recent call last):
File "[PATH_TO_MODULE1]/server_run.py", line 1, in <module>
from configuration.constants import *
File "[PATH_TO_MODULE2]/constants.py", line 1, in <module>
from config import *
ModuleNotFoundError: No module named 'config'
So, it looks like when I'm trying to start my server in subprocess it doesn't see imports anymore.
Do you guys have any idea how can I fix it?
Eventually, the solution was found, 2 steps were taken:
1. In each module I had an empty __init__.py file, it was changed to:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
__version__ = '${version}'
2. Instead of using the following syntax:
from configuration.constants import *
from configuration.config import *
config and constants were imported as:
from configuration import constants,config
and then we are using reference to them when need to get some constant.
Thanks everyone for looking into it.
Rather than running it using os module try using the import function. You will need to save in the same dictionary or a sub folder or the python installation but this seems to be the way to do it. Like this post suggests.

web2py Can't import run functions from imported module

I'm trying to import external modules into my controller code for a web2py application. The module I'm importing is located in myapp/modules and seems to import fine. However, it doesn't let me call any of the functions defined in there; gives the following error
'module' object has no attribute 'testfunc'
I'm importing like this:
import json_utils as u
And calling like this:
u.testfunc()
Am I missing something obvious here? I have tried stop/starting the server in case its not reloaded the file.
Cheers
EDIT: Here is the entire json_utils.py file:
def testfunc():
return 3
def testfunc2():
# some stuff
return 5
Problem is web2py caching external modules. Stop/Starting the server is not enough, I need to kill the whole thing are reboot.
It's saying that json_utils has no function called testfunc
The module json_utils has no built-in function testfunc()
for example if I do
import random
u.nonfunction()
and then I run it I get
AttributeError: 'module' object has no attribute 'nonfunction'
but if I do a function that it has
import random
random = u.randrange(1,10)
print(random)
It works properly

Python "import random" Error

As you may know from my previous posts, I'm learning Python. And this time I have a small error which I think is with this build of Python itself. When using the following:
import random
number = random.randint(1,10000)
Python gives me this error:
File "C\Users\name\Documents\Python\random.py", line 5, in (module)
print random.random()
TypeError: 'module' object is not callable
Every time I try to run it. Me no understand. Any help would be much appreciated!
EDIT: The two lines of code I'm trying to run:
import random
print random.randint(1,100)
That's it. And it gives me the same error.
By naming your script random.py, you've created a naming conflict with the random standard library module.
When you try to run your script, the directory containing the script will be added to the start of the module import path. So when your script does import random, you're effectively running a second copy of the script as the random module.
When the random module runs import random, it means that random.random will also be a reference to your module. So when you attempt to call the random.random() standard library function, you're actually attempting to call the module object resulting in the error you got.
If you rename your script to something else, the problem should go away.
Even I faced the same problem. I have renamed my python file from random.py to shuffle.py. This didn't work out. Then I changed the version then it worked. This may help a bit.
Python version : 3.6.7
replace
import random;
to
import random2;
I am using pycharm and I had to take the additional step to import the methods from random. In my case:
import random
from random import choice
The simple answer: Change your filename from "random.py" to something else as it is conflicting with random library.

Python Idle and Terminal Import Differences

I just started using Python and I have a question about idle vs terminal.
In idle, I made a file called Robot.py
I have a class called Robot
class Robot(object)
def __init__(self,x,y):
#some code here etc...
def HelloWorld()
print "Hello World!"
I have another file called testrobot.py, which looks like so:
import Robot
r = Robot(1,4)
In idle, I am able to successfully create a Robot object when I run testrobot.py. However in terminal, it gives an error Message NameError: Robot is not defined
I'm not sure how to run my program in terminal.
Also:
How can I call my HelloWorld() function which is in Robots.py but not of the class Robot in an external file (such as testrobot.py)?
Thanks in advance!
When you load and run scripts in IDLE, they are automatically loaded for the interpreter. That means that as soon as you run the script in IDLE, the Python shell already has those types defined.
When you want to run it from outside of IDLE, i.e. without running the module first, you need to import your Robot from that module. To do that, you import the module, not the type:
import Robot
myRobot = Robot.Robot(...)
Or, if you want to use Robot directly, you need to use the from ... import syntax:
from Robot import Robot
myRobot = Robot(...)
Similarily, you can call your function by using Robot.HelloWorld in the first case, or directly if you add HelloWorld to the import list in the second case:
from Robot import Robot, HelloWorld
myRobot = Robot(...)
HelloWorld()
As you can see, it is generally a good idea to name your files in lower case, as those are the module names (or “namespaces” in other languages).
You are trying to create a class of an import, not the class imported.
You are trying to import a file called Robot.py with that import statement. To import your robot class you will have to type import Robot and then write Robot.Robot(1,4) to create an object of it. Alternatively you can import all references from the file: from Robot import * and then write Robot(1,4).
The reason it will work with IDLE is that it basically imports everything from the file you run, allowing you use the methods and classes in that file.

Categories