Import issues in Visual Studio Code - python

I am trying to execute this code in Visual Studio Code, the code works, my problem is related to the import of numpy; the other imports are working.
import codecs
from operator import le
import string
from struct import unpack
import paho.mqtt.client as mqtt
import struct
import numpy as np
def on_connect1(client1, userdata1, flags1, rc1):
client1.subscribe("MYTOPIC")
def on_message1(client1, userdata1, msg1):
#print(msg1.topic+" "+ "TERMORESISTENZA: "+str(msg1.payload))
Byte_Order = '<' # little-endian
Format_Characters = 'f' # float (4 bytes)
data_format = Byte_Order + Format_Characters
r = np.array(list(struct.iter_unpack(data_format, msg1.payload)), dtype=float)
print(r)
When I run the code it returns me this error:
ModuleNotFoundError: No module named 'numpy'
Any suggestions?

I used the Windows Command Prompt to install numpy with the command:
pip install numpy
and solved the problem

Related

Linux: SyntaxError for error-free Python script

I am trying to run a python file that works fine on my Windows machine on a remote server:
import collections
import pandas as pd
from pathlib import Path
import shelve
import cloudpickle
import numpy as np
import typing
from typing import List
import ray
from ray.rllib.agents import ppo
from ray.rllib.utils.spaces.space_utils import flatten_to_single_ndarray
from ray.tune import register_env
from ray.rllib.env.base_env import _DUMMY_AGENT_ID
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID
.
.
.
if __name__ == '__main__':
WIN = False
ray.init(dashboard_port=8263)
daterange = pd.date_range('2017-01-01', periods=35040, freq='15T')
norming_factor = 10
actions_module = ActionsModuleContinuous()
batch_n_days = 1
kappa = 1000
seed = 1234
steps_per_episode = batch_n_days * 24 * 4
num_episodes = 5
device_config: List = list()
device_config.append(Device1(WIN=WIN, norming_factor=norming_factor, n_data_points=steps_per_episode))
device_config.append(Device2(WIN=WIN))
device_config.append(Device3(WIN=WIN))
It returns the following SyntaxError, for no apparent reason:
(venv) [<username>#<server> examples]$ python test.py
File "test.py", line 183
device_config: List = list()
^
SyntaxError: invalid syntax
I have tried deleting : List, which just had the effect of moving the same error to a seemingly arbitrary place further down the script. Any help is greatly appreciated.
device_config: List = list()
That syntax is adding type annotations for variable device_config.
If you get SyntaxError: invalid syntax exception, it means that your python interpreter used to run your code is not new enough. Nothing to do with your code, it just means that when you enter python in your shell, interpreter that gets executed is not new enough.

How to import "gleam" package in Python 3?

I'm tyring to import the "gleam" package in Python 3. I have installed the "gleam" package successfully, but still it showing error.
from wtforms import fields
from ggplot import *
from gleam import Page, panels
class ScatterInput(panels.Inputs):
title = fields.StringField(label="Title of plot:")
yvar = fields.SelectField(label="Y axis",
choices=[("beef", "Beef"),
("pork", "Pork")])
smoother = fields.BooleanField(label="Smoothing Curve")
class ScatterPlot(panels.Plot):
name = "Scatter"
def plot(self, inputs):
p = ggplot(meat, aes(x='date', y=inputs.yvar))
if inputs.smoother:
p = p + stat_smooth(color="blue")
p = p + geom_point() + ggtitle(inputs.title)
return p
class ScatterPage(Page):
input = ScatterInput()
output = ScatterPlot()
ScatterPage.run()
Error:
ModuleNotFoundError - Traceback (most> recent call last) in ()
----> 1 import gleam
C:\pythonNJ\lib\site-packages\gleam__init__.py in ()
5 import os
6 import json
----> 7 import urlparse
8 from collections import namedtuple
9
ModuleNotFoundError: No module named 'urlparse'
I looked for the solution and I found that urlparse has been moved to a new module in python 3, which can be imported as
from urllib.parse import urlparse
And I even imported it, but still when I trying to import "gleam" package it shows error of module "urlparse". Can you suggest me how to bypass it (bypassing import urlparse statement and importing gleam package in Python 3).
I know how to import the urlparse but I don't know how to import the gleam package.
You have two possiblities:
Modify source code yourself as you stated inside gleam package, but it could work incorrectly.
Fall back to version of python it works on - so 2.7 it seems, since the modification you mentioned was done with python 3.0 release. It's stated in docs here.
Just do this to get over it:
from:
import urlparser
to:
import urllib.parse

Import image in python

hello I am a beginner in python and I have problems executing my code .
how can i fix this error with python:
import cgitb
cgitb.enable()
print('Content-type: text/html\r\n')
print('\r\n')
import Image, ImageDraw
import sys
import math, random
from itertools import product
from ufarray import *
ModuleNotFoundError: No module named 'Image'
args = ("No module named 'Image'",)
msg = "No module named 'Image'"
name = 'Image'
path = None
with_traceback = <built-in method with_traceback of ModuleNotFoundError
Make sure you have installed Pillow (the supported, open-source version of the PIL Python Image Library) and then change your import to:
from PIL import Image, ImageDraw
That should get you farther along.
Try this:
from PIL import Image
or else you haven't installed it yet:
pip install pillow
I had a similar Problem, this post helped me: How to insert an image in python
What they basically use is:
import Image
myImage = Image.open("your_image_here");
myImage.show();
For more help I would need your full code. Even after the edit it is not quite clear to me what is your code, what is the error and what you are actually trying to do.

Python cannot import from another file name not defined

I am trying to import a custom function from another python file but keep getting an error NameError: name 'testme' is not defined. I confirmed that I am importing the file correctly according to this SO post and that the function is top level. What else can I try to fix this?
My main python file is:
import sys
import dbconn
#from dbconn import testme #<----did not work
dev=True
if(dev):
categId='528'
pollIds=[529,530,531]
else:
categId=str(sys.argv[1])
pollIds=[529,530,531]
df=testme(categIds)#callServer(categId,pollIds)
df
if(not categId.isdigit):
print('categ id fail. expected digit got: '+categId)
.....
and dbconn.py:
import pymysql #pip3 install PyMySQL
import pandas as pd
from scipy.stats.stats import pearsonr
from scipy import stats
def testme(categIds):
try:
df=categIds
except Exception as e:
print("broke")
return categIds
Not sure if it makes a difference but I am running the main python file from within a Jupyter notebook, and have a compiled version of dbconn.py in the same directory
In response to the suggestions I tried:
df=dbconn.testme(categIds)
got the error:
module 'dbconn' has no attribute 'testme'
You Have to follow these fox exact import
1)import <package>
2)import <module>
3)from <package> import <module or subpackage or object>
4)from <module> import <object>
in your case, you have tried
from dbconn import testme
you have to use only packages in from section and module in import section
like >>
from testme import dbconn

Trouble to impliment scipy interpolation

I am trying to use the class shown here to interpolate some data.
I am having trouble getting this class to work. A minimal example is:
#!/usr/bin/env python
import sys
from mayavi.mlab import *
from mayavi import mlab
from numpy import *
import numpy as np
from mayavi.scripts import mayavi2
from mayavi.sources.vtk_file_reader import VTKFileReader
from mayavi.modules.outline import Outline
from mayavi.modules.grid_plane import GridPlane
from mayavi.modules.contour_grid_plane import ContourGridPlane
from mayavi.modules.iso_surface import IsoSurface
from mayavi.modules.scalar_cut_plane import ScalarCutPlane
import scipy
from scipy import interpolate
from scipy.interpolate import griddata
#from scipy.interpolate import RegularGridInterpolator
print 'Argument List:', str(sys.argv)
if (len(sys.argv)==5):
NX = int(sys.argv[1])
NY = int(sys.argv[2])
NZ = int(sys.argv[3])
fname = sys.argv[4]
else:
print "Error in parsing the command line arguments"
print "Command line arguments are: N_X N_Y N_Z filename "
sys.exit()
clf()
figure(bgcolor=(1, 1, 1))
len(sys.argv)
data = genfromtxt(fname)
x,y,z = mgrid[ 0:NX:1, 0:NY:1, 0:NZ:1 ]
#print(x)
index = 0
V=0*x
for k in range(NZ):
for j in range(NY):
for i in range(NX):
V[i][j][k] = 1000*data[index,5]
scipy.interpolate.RegularGridInterpolator(V, V, method='linear', bounds_error=True, fill_value=nan) #ERROR
The only bits really of interest to my current problem are the last line and all the import commands at the beginning
My error is:
Traceback (most recent call last):
File "contour-3d.py", line 70, in <module>
scipy.interpolate.RegularGridInterpolator(W, W, method='linear', bounds_error=True, fill_value=nan)
AttributeError: 'module' object has no attribute 'RegularGridInterpolator'
I'm not too familiar with python, so this may be a very basic error.
From the docs:
New in version 0.14.
It's likely you have a previous version of SciPy. If you are using Ubuntu, try running pip:
pip install --user --upgrade scipy
You might need some additional dependencies:
sudo apt-get install gcc gfortran python-dev libblas-dev liblapack-dev cython
For more information see http://www.scipy.org/install.html and http://www.scipy.org/scipylib/building/
scipy.interpolate.RegularGridInterpolator is a new function in scipy 0.14.x. You are likely to be using a older version. Updating scipy should solve the problem.

Categories