Related
This question already has answers here:
Need to Install PyOpenGL (Windows)
(1 answer)
PyOpenGL glutInit NullFunctionError
(14 answers)
Attempt to call an undefined function glutInit
(2 answers)
Closed 2 years ago.
I have a project when I need to do boolean operations with 3D models (CGS mainly), and I was trying to implement the example given on the library for python but it is not working. Seems like the code runs on OpenGL and the error comes from it instead of the example.
Anybody has an idea of how to make it work?
What am I missing?
Here is the error I get and the library link is below.
OpenGL.error.NullFunctionError: Attempt to call an undefined function
glutInit, check for bool(glutInit) before calling
Library link: https://github.com/timknip/pycsg
Example code
import sys
import os
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
sys.path.insert(0, os.getcwd())
from csg.core import CSG
from csg.geom import Vertex, Vector
from optparse import OptionParser
light_ambient = [0.3, 0.3, 0.3, 1.0]
light_diffuse = [0.7, 0.7, 0.7, 1.0] # Red diffuse light
light_position = [100.0, 100.0, 100.0, 0.0] # Infinite light location.
rot = 0.0
class TestRenderable(object):
def __init__(self, operation):
self.faces = []
self.normals = []
self.vertices = []
self.colors = []
self.vnormals = []
self.list = -1
a = CSG.cube()
b = CSG.cylinder(radius=0.5, start=[0., -2., 0.], end=[0., 2., 0.])
for p in a.polygons:
p.shared = [1.0, 0.0, 0.0, 1.0]
for p in b.polygons:
p.shared = [0.0, 1.0, 0.0, 1.0]
recursionlimit = sys.getrecursionlimit()
sys.setrecursionlimit(10000)
try:
if operation == 'subtract':
polygons = a.subtract(b).toPolygons()
elif operation == 'union':
polygons = a.union(b).toPolygons()
elif operation == 'intersect':
polygons = a.intersect(b).toPolygons()
else:
raise Exception('Unknown operation: \'%s\'' % operation)
except RuntimeError as e:
raise RuntimeError(e)
sys.setrecursionlimit(recursionlimit)
for polygon in polygons:
n = polygon.plane.normal
indices = []
for v in polygon.vertices:
pos = [v.pos.x, v.pos.y, v.pos.z]
if not pos in self.vertices:
self.vertices.append(pos)
self.vnormals.append([])
index = self.vertices.index(pos)
indices.append(index)
self.vnormals[index].append(v.normal)
self.faces.append(indices)
self.normals.append([n.x, n.y, n.z])
self.colors.append(polygon.shared)
# setup vertex-normals
ns = []
for vns in self.vnormals:
n = Vector(0.0, 0.0, 0.0)
for vn in vns:
n = n.plus(vn)
n = n.dividedBy(len(vns))
ns.append([a for a in n])
self.vnormals = ns
def render(self):
if self.list < 0:
self.list = glGenLists(1)
glNewList(self.list, GL_COMPILE)
for n, f in enumerate(self.faces):
glMaterialfv(GL_FRONT, GL_DIFFUSE, self.colors[n])
glMaterialfv(GL_FRONT, GL_SPECULAR, self.colors[n])
glMaterialf(GL_FRONT, GL_SHININESS, 50.0)
glColor4fv(self.colors[n])
glBegin(GL_POLYGON)
if self.colors[n][0] > 0:
glNormal3fv(self.normals[n])
for i in f:
if self.colors[n][1] > 0:
glNormal3fv(self.vnormals[i])
glVertex3fv(self.vertices[i])
glEnd()
glEndList()
glCallList(self.list)
renderable = None
def init():
# Enable a single OpenGL light.
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient)
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse)
glLightfv(GL_LIGHT0, GL_POSITION, light_position)
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
# Use depth buffering for hidden surface elimination.
glEnable(GL_DEPTH_TEST);
# Setup the view of the cube.
glMatrixMode(GL_PROJECTION);
gluPerspective(40.0, 640./480., 1.0, 10.0);
glMatrixMode(GL_MODELVIEW);
gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.)
def display():
global rot
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glPushMatrix()
glTranslatef(0.0, 0.0, -1.0);
glRotatef(rot, 1.0, 0.0, 0.0);
glRotatef(rot, 0.0, 0.0, 1.0);
rot += 0.1
renderable.render()
glPopMatrix()
glFlush()
glutSwapBuffers()
glutPostRedisplay()
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-o', '--operation', dest='operation',
type='str', default='subtract')
(options, args) = parser.parse_args()
renderable = TestRenderable(options.operation)
glutInit()
glutInitWindowSize(640,480)
glutCreateWindow("CSG Test")
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA)
glutDisplayFunc(display)
init()
glutMainLoop()
There is a issue when installing pyopengl with pip install pyopengl on Windows systems.
Go to Unofficial Windows Binaries for Python Extension Packages
Download a 32 bit or 64 bit package for PyOpenGL provides bindings to OpenGL, GLUT, and GLE
(e.g.
PyOpenGL‑3.1.5‑cp39‑cp39‑win_amd64.whl and
PyOpenGL_accelerate‑3.1.5‑cp39‑cp39‑win_amd64.whl)
Open Command Prompt (cmd.exe) as administrator. Change to the download directory and install the packages by pip install packagename.whl.
e.g:
pip install PyOpenGL‑3.1.5‑cp39‑cp39‑win_amd64.whl
and
pip install PyOpenGL_accelerate‑3.1.5‑cp39‑cp39‑win_amd64.whl
If the package is already installed, but doesn't work, then you have to ignore the currently installed package, by the option --ignore-installed:
pip install --ignore-installed PyOpenGL‑3.1.5‑cp39‑cp39‑win_amd64.whl
pip install --ignore-installed PyOpenGL_accelerate‑3.1.5‑cp39‑cp39‑win_amd64.whl
I have written this GPU code in C using GLES and EGL, and it ran fine. I am now trying to port this GPU code to python using ModernGL, except right after I call the render function, ctx returns a GL_INVALID_ENUM error. I am using a NanoPi M1 Plus with Mali400 GPU which supports only OpenGL version 120.
GPU CODE:
import moderngl
import numpy as np
ctx = moderngl.create_context(standalone=True,
backend='egl'
)
prog = ctx.program(
vertex_shader='''
#version 120
attribute vec4 vPosition;
void main() {
gl_Position = vPosition;
}
''',
fragment_shader='''
#version 120
uniform float Aarr[1000];
void main() {
int my_index = int(gl_FragCoord[0]);
float ex = exp(-Aarr[my_index]);
float result = 1 / (1.0 + ex);
gl_FragColor = vec4(result, 0.0, 0.0, 1.0);
}
''',
)
vertices = np.array([
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
1.0, -1.0, 1.0
],
dtype='f4',
)
vbo = ctx.buffer(vertices)
vao = ctx.simple_vertex_array(prog, vbo, 'vPosition')
A_vec = prog['Aarr']
A_vec.write(np.random.uniform(-256,256,[1000]).astype('f4'))
fbo = ctx.simple_framebuffer((1000, 2), components=4)
fbo.use()
fbo.clear(0.0, 0.0, 0.0, 1.0)
vao.render()
print("Error after render: ",ctx.error)
Output:
libGL error: MESA-LOADER: malformed or no PCI ID
libGL error: unable to load driver: mali_drm_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: mali_drm
Error after render: GL_INVALID_ENUM
Any help would be greatly appreciated as this is required for my final year project.
Mali400 GPU which supports only OpenGL version 120
It doesn't support OpenGL at all; it supports OpenGL ES 1.1 and 2.0.
Is there a better or shorter way to write this code?
def business_role_code_to_name(x):
y = []
for position, code in enumerate(x):
if position == 0 and code == 1.0:
y.append("Owner")
elif position == 1 and code == 1.0:
y.append("Manager")
elif position == 2 and code == 1.0:
y.append("Employee")
elif position == 3 and code == 1.0:
y.append("Other")
return y
assert business_role_code_to_name([1.0, 1.0, 1.0, 0.0]) == ['Owner', 'Manager', 'Employee']
assert business_role_code_to_name([0.0, 1.0, 0.0, 1.0]) == ['Manager', 'Other']
I am new to programming, I think there is a better way to write this code. Thanks!
Try using:
def business_role_code_to_name(x):
y = []
d = {(0, 1): 'Owner', (1, 1): 'Manager', (2, 1): 'Employee', (3, 1): 'Other'}
for i in enumerate(x):
if d.get(i):
y.append(d[i])
return y
Use itertools.compress:
from itertools import compress
names = ['Owner', 'Manager', 'Employee', 'Other']
positions_0 = [1.0, 1.0, 1.0, 0.0]
positions_1 = [0.0, 1.0, 0.0, 1.0]
Output:
list(compress(names, positions_0))
# ['Owner', 'Manager', 'Employee']
list(compress(names, positions_1))
# ['Manager', 'Other']
The function business_role_code_to_name has the same logic as below
def business_role_code_to_name(x):
z = ['Owner', 'Manager', 'Employee' ,'Other']
y = [z[position] for position, code in enumerate(x) if code==1.0]
return y
You might use zip for that task following way:
roles = ["Owner","Manager","Employee","Other"]
code1 = [1.0, 1.0, 1.0, 0.0]
code2 = [0.0, 1.0, 0.0, 1.0]
def decode_role(rolecode):
return [role for code,role in zip(rolecode,roles) if code==1.0]
print(decode_role(code1)) # ['Owner', 'Manager', 'Employee']
print(decode_role(code2)) # ['Manager', 'Other']
I have written an example with error handling:
Function:
def business_role_code_to_name(x):
y = []
positions = {0: "Owner", 1: "Manager", 2: "Employee", 3: "Other"}
for position, code in enumerate(x):
if code != 1.0:
continue
try:
y.append(positions[position])
except KeyError as key_err:
print("{} is a wrong index.".format(position))
raise key_err
return y
Test:
print(business_role_code_to_name([1.0, 1.0, 1.0, 0.0]))
print(business_role_code_to_name([0.0, 1.0, 0.0, 1.0]))
print(business_role_code_to_name([0.0, 1.0, 0.0, 1.0, 1.0]))
Output:
>>> python3 test.py
['Owner', 'Manager', 'Employee']
['Manager', 'Other']
4 is a wrong index.
Traceback (most recent call last):
File "test.py", line 21, in <module>
print(business_role_code_to_name([0.0, 1.0, 0.0, 1.0, 1.0]))
File "test.py", line 11, in business_role_code_to_name
raise key_err
File "test.py", line 8, in business_role_code_to_name
y.append(positions[position])
KeyError: 4
You can do it like this without foor loops:
roles = ('Owner', 'Manager', 'Employee', 'Other')
def business_role_code_to_name(x):
positions = filter(lambda k: x[k] == 1.0, range(len(x)))
return list(map(roles.__getitem__, positions))
I'm using a BCF2000 Behringer fader as input to control a robot using ROS. Everything was working fine, but suddenly it stopped working. By suddenly I mean after I got to word after a week off. I need to know if it's a hardware or software problem (maybe somebody drop it off while I was gone? I don't think so but I cannot find a bug). I'm running only a python module that reads the data from the fader and publishes it in ROS to find the problem, which is that I cannot make the sliders of the fader move.
Basically, the python module reads two integers from the argument list. If a third one is given, all values of the fader should be put to 0 (sliders and buttons). The first integer is the input device id, and the second is the output device id. This is:
if len(sys.argv) > 1:
input_dev = int(sys.argv[1])
else:
input_dev = pygame.midi.get_default_input_id()
print "Using DEFAULT input device %d" % input_dev
if input_dev == -1:
print "No default MIDI input device"
exit(-1)
print "Using input device %d" % input_dev
if len(sys.argv) > 2:
output_dev = int(sys.argv[2])
else:
output_dev = pygame.midi.get_default_output_id()
print "Using DEFAULT output device %d" % input_dev
if output_dev == -1:
print "No default MIDI output device"
exit(-1)
print "Using output device %d" % output_dev
controller = pygame.midi.Input(input_dev)
controller_input = pygame.midi.Output(output_dev)
The thing is that I don't know how to find the correct input device number. For the last month I was calling it using '3' and '2', meaning:
me#mycpu:ros$ rosrun bcf2000 bcf2000_driver.py 3 2
if I make an echo of the published data, I get all the data published when I move any slider or press a button. For example:
me#mycpu:ros$ rostopic echo /bcf2000/joy
header:
seq: 1
stamp:
secs: 1441969279
nsecs: 677656888
frame_id: ''
axes: [21.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 69.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
buttons: [127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
but if I write to the fader, the sliders won't move. Again, this code was working a few days ago. I'm 100% sure is the same code according to the GIT repository log. For example, putting everything to 0:
for i in range(1,93):
controller_input.write([[[176, i, 0, 0], 0]])
where the fader has 93 channels.
It may be that I'm using the wrong output device number. I've changed the number between 0 and 10 and nothing. How do I find out what is the correct device number? How do I debug that is actually a software issue (maybe a OS issue, I don't know) or a hardware issue? The last is very unlikely, since it would be a very selective hardware issue. But I may be mistake.
UPDATE: This only happens on my computer, so it's not a hardware issue.
UPDATE 2: This is the output of aseqdump -l
me#mycpu:ros$ aseqdump -l
Port Client name Port name
0:0 System Timer
0:1 System Announce
14:0 Midi Through Midi Through Port-0
24:0 BCF2000 BCF2000 MIDI 1
24:1 BCF2000 BCF2000 MIDI 2
I can listen to the input using aseqdump -p 24:0.
Listing the info from all devices using get_device_info gives:
('ALSA', 'Midi Through Port-0', 0, 1, 0)
('ALSA', 'Midi Through Port-0', 1, 0, 0)
('ALSA', 'BCF2000 MIDI 1', 0, 1, 0)
('ALSA', 'BCF2000 MIDI 1', 1, 0, 0)
('ALSA', 'BCF2000 MIDI 2', 0, 1, 0)
('ALSA', 'BCF2000 MIDI 2', 1, 0, 0)
('ALSA', 'BCF2000 MIDI 3', 0, 1, 0)
('ALSA', 'aseqdump', 0, 1, 0)
For devices 2, 4 and 6 I cannot write to the device. I'm trying to write to each output device using:
#!/usr/bin/env python
import pygame
import pygame.midi
import sys
import time
def main():
pygame.midi.init()
devices = pygame.midi.get_count()
if devices < 1:
print "No MIDI devices detected"
exit(-1)
print "Found %d MIDI devices" % devices
print("id -- interface -- name -- input -- ouput -- opened")
for ii in range(devices):
ll = pygame.midi.get_device_info(ii)
bool1 = bool(ll[2])
bool2 = bool(ll[3])
bool3 = bool(ll[4])
print(str(ii) + " -- " + str(ll[0]) + " -- " + str(ll[1]) + " -- " + str(bool1) + " -- " + str(bool2) + " -- " + str(bool3))
if (bool2):
value = 0
if ii%2 == 0:
value = 127
controller = pygame.midi.Output(ii)
controller.write([[[176, 48, 0, 0], value]])
time.sleep(2)
which should print the device info for each device, and if its an output device, it should move the first slider. It doesn't move for any device.
I am receiving the following error when importing pandas in a Python program
monas-mbp:book mona$ sudo pip install python-dateutil
Requirement already satisfied (use --upgrade to upgrade): python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
Cleaning up...
monas-mbp:book mona$ python t1.py
No module named dateutil.parser
Traceback (most recent call last):
File "t1.py", line 4, in <module>
import pandas as pd
File "/Library/Python/2.7/site-packages/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
File "tslib.pyx", line 31, in init pandas.tslib (pandas/tslib.c:48782)
ImportError: No module named dateutil.parser
Also here's the program:
import codecs
from math import sqrt
import numpy as np
import pandas as pd
users = {"Angelica": {"Blues Traveler": 3.5, "Broken Bells": 2.0,
"Norah Jones": 4.5, "Phoenix": 5.0,
"Slightly Stoopid": 1.5,
"The Strokes": 2.5, "Vampire Weekend": 2.0},
"Bill":{"Blues Traveler": 2.0, "Broken Bells": 3.5,
"Deadmau5": 4.0, "Phoenix": 2.0,
"Slightly Stoopid": 3.5, "Vampire Weekend": 3.0},
"Chan": {"Blues Traveler": 5.0, "Broken Bells": 1.0,
"Deadmau5": 1.0, "Norah Jones": 3.0, "Phoenix": 5,
"Slightly Stoopid": 1.0},
"Dan": {"Blues Traveler": 3.0, "Broken Bells": 4.0,
"Deadmau5": 4.5, "Phoenix": 3.0,
"Slightly Stoopid": 4.5, "The Strokes": 4.0,
"Vampire Weekend": 2.0},
"Hailey": {"Broken Bells": 4.0, "Deadmau5": 1.0,
"Norah Jones": 4.0, "The Strokes": 4.0,
"Vampire Weekend": 1.0},
"Jordyn": {"Broken Bells": 4.5, "Deadmau5": 4.0,
"Norah Jones": 5.0, "Phoenix": 5.0,
"Slightly Stoopid": 4.5, "The Strokes": 4.0,
"Vampire Weekend": 4.0},
"Sam": {"Blues Traveler": 5.0, "Broken Bells": 2.0,
"Norah Jones": 3.0, "Phoenix": 5.0,
"Slightly Stoopid": 4.0, "The Strokes": 5.0},
"Veronica": {"Blues Traveler": 3.0, "Norah Jones": 5.0,
"Phoenix": 4.0, "Slightly Stoopid": 2.5,
"The Strokes": 3.0}
}
class recommender:
def __init__(self, data, k=1, metric='pearson', n=5):
""" initialize recommender
currently, if data is dictionary the recommender is initialized
to it.
For all other data types of data, no initialization occurs
k is the k value for k nearest neighbor
metric is which distance formula to use
n is the maximum number of recommendations to make"""
self.k = k
self.n = n
self.username2id = {}
self.userid2name = {}
self.productid2name = {}
# for some reason I want to save the name of the metric
self.metric = metric
if self.metric == 'pearson':
self.fn = self.pearson
#
# if data is dictionary set recommender data to it
#
if type(data).__name__ == 'dict':
self.data = data
def convertProductID2name(self, id):
"""Given product id number return product name"""
if id in self.productid2name:
return self.productid2name[id]
else:
return id
def userRatings(self, id, n):
"""Return n top ratings for user with id"""
print ("Ratings for " + self.userid2name[id])
ratings = self.data[id]
print(len(ratings))
ratings = list(ratings.items())
ratings = [(self.convertProductID2name(k), v)
for (k, v) in ratings]
# finally sort and return
ratings.sort(key=lambda artistTuple: artistTuple[1],
reverse = True)
ratings = ratings[:n]
for rating in ratings:
print("%s\t%i" % (rating[0], rating[1]))
def loadBookDB(self, path=''):
"""loads the BX book dataset. Path is where the BX files are
located"""
self.data = {}
i = 0
#
# First load book ratings into self.data
#
f = codecs.open(path + "BX-Book-Ratings.csv", 'r', 'utf8')
for line in f:
i += 1
#separate line into fields
fields = line.split(';')
user = fields[0].strip('"')
book = fields[1].strip('"')
rating = int(fields[2].strip().strip('"'))
if user in self.data:
currentRatings = self.data[user]
else:
currentRatings = {}
currentRatings[book] = rating
self.data[user] = currentRatings
f.close()
#
# Now load books into self.productid2name
# Books contains isbn, title, and author among other fields
#
f = codecs.open(path + "BX-Books.csv", 'r', 'utf8')
for line in f:
i += 1
#separate line into fields
fields = line.split(';')
isbn = fields[0].strip('"')
title = fields[1].strip('"')
author = fields[2].strip().strip('"')
title = title + ' by ' + author
self.productid2name[isbn] = title
f.close()
#
# Now load user info into both self.userid2name and
# self.username2id
#
f = codecs.open(path + "BX-Users.csv", 'r', 'utf8')
for line in f:
i += 1
#print(line)
#separate line into fields
fields = line.split(';')
userid = fields[0].strip('"')
location = fields[1].strip('"')
if len(fields) > 3:
age = fields[2].strip().strip('"')
else:
age = 'NULL'
if age != 'NULL':
value = location + ' (age: ' + age + ')'
else:
value = location
self.userid2name[userid] = value
self.username2id[location] = userid
f.close()
print(i)
def pearson(self, rating1, rating2):
sum_xy = 0
sum_x = 0
sum_y = 0
sum_x2 = 0
sum_y2 = 0
n = 0
for key in rating1:
if key in rating2:
n += 1
x = rating1[key]
y = rating2[key]
sum_xy += x * y
sum_x += x
sum_y += y
sum_x2 += pow(x, 2)
sum_y2 += pow(y, 2)
if n == 0:
return 0
# now compute denominator
denominator = (sqrt(sum_x2 - pow(sum_x, 2) / n)
* sqrt(sum_y2 - pow(sum_y, 2) / n))
if denominator == 0:
return 0
else:
return (sum_xy - (sum_x * sum_y) / n) / denominator
def computeNearestNeighbor(self, username):
"""creates a sorted list of users based on their distance to
username"""
distances = []
for instance in self.data:
if instance != username:
distance = self.fn(self.data[username],
self.data[instance])
distances.append((instance, distance))
# sort based on distance -- closest first
distances.sort(key=lambda artistTuple: artistTuple[1],
reverse=True)
return distances
def recommend(self, user):
"""Give list of recommendations"""
recommendations = {}
# first get list of users ordered by nearness
nearest = self.computeNearestNeighbor(user)
#
# now get the ratings for the user
#
userRatings = self.data[user]
#
# determine the total distance
totalDistance = 0.0
for i in range(self.k):
totalDistance += nearest[i][1]
# now iterate through the k nearest neighbors
# accumulating their ratings
for i in range(self.k):
# compute slice of pie
weight = nearest[i][1] / totalDistance
# get the name of the person
name = nearest[i][0]
# get the ratings for this person
neighborRatings = self.data[name]
# get the name of the person
# now find bands neighbor rated that user didn't
for artist in neighborRatings:
if not artist in userRatings:
if artist not in recommendations:
recommendations[artist] = (neighborRatings[artist]
* weight)
else:
recommendations[artist] = (recommendations[artist]
+ neighborRatings[artist]
* weight)
# now make list from dictionary
recommendations = list(recommendations.items())
recommendations = [(self.convertProductID2name(k), v)
for (k, v) in recommendations]
# finally sort and return
recommendations.sort(key=lambda artistTuple: artistTuple[1],
reverse = True)
# Return the first n items
return recommendations[:self.n]
r = recommender(users)
# The author implementation
r.loadBookDB('/Users/mona/Downloads/BX-Dump/')
ratings = pd.read_csv('/Users/danialt/BX-CSV-Dump/BX-Book-Ratings.csv', sep=";", quotechar="\"", escapechar="\\")
books = pd.read_csv('/Users/danialt/BX-CSV-Dump/BX-Books.csv', sep=";", quotechar="\"", escapechar="\\")
users = pd.read_csv('/Users/danialt/BX-CSV-Dump/BX-Users.csv', sep=";", quotechar="\"", escapechar="\\")
pivot_rating = ratings.pivot(index='User-ID', columns='ISBN', values='Book-Rating')
On Ubuntu you may need to install the package manager pip first:
sudo apt-get install python-pip
Then install the python-dateutil package with:
sudo pip install python-dateutil
For Python 3:
pip3 install python-dateutil
You can find the dateutil package at https://pypi.python.org/pypi/python-dateutil. Extract it to somewhere and run the command:
python setup.py install
It worked for me!
I have same issues on my MacOS and it's work for me to try
pip3 install python-dateutil
on Ubuntu
sudo apt-get install python-dateutil
For Python 3 above, use:
sudo apt-get install python3-dateutil
If you're using a virtualenv, make sure that you are running pip from within the virtualenv.
$ which pip
/Library/Frameworks/Python.framework/Versions/Current/bin/pip
$ find . -name pip -print
./flask/bin/pip
./flask/lib/python2.7/site-packages/pip
$ ./flask/bin/pip install python-dateutil
None of the solutions worked for me. If you are using PIP do:
pip install pycrypto==2.6.1
In Ubuntu 18.04 for Python2:
sudo apt-get install python-dateutil
I had the similar problem. This is the stack trace:
Traceback (most recent call last):
File "/usr/local/bin/aws", line 19, in <module> import awscli.clidriver
File "/usr/local/lib/python2.7/dist-packages/awscli/clidriver.py", line 17, in <module> import botocore.session
File "/usr/local/lib/python2.7/dist-packages/botocore/session.py", line 30, in <module> import botocore.credentials
File "/usr/local/lib/python2.7/dist-packages/botocore/credentials.py", line 27, in <module> from dateutil.parser import parse
ImportError: No module named dateutil.parser
I tried to (re-)install dateutil.parser through all possible ways. It was unsuccessful.
I solved it with
pip3 uninstall awscli
pip3 install awscli
sudo python3 -m pip install PyPDF2 passlib babel werkzeug lxml decorator polib pillow psycopg2 idna python-dateutil psutil requests jinja2
If you are using Pipenv, you may need to add this to your Pipfile:
[packages]
python-dateutil = "*"