'Cannot import name games' - python

I'm a beginner and so far I have about 3 hours invested installing pygame( ie getting the python interpreter to accept 'from livewires import games, color' to check both 'pygame' and 'livewires' have installed).
However, when I ran my first source code I got this:
Traceback (most recent call last):
File "C:/Python31/Coding/pygame.py", line 4, in <module>
from livewires import games
File "C:\Python31\lib\site-packages\livewires\games.py", line 57, in <module>
import pygame, pygame.image, pygame.mixer, pygame.font, pygame.transform
File "C:/Python31/Coding\pygame.py", line 4, in <module>
from livewires import games
ImportError: cannot import name games
>>>
Why might this be happening? Does anyone have some pointers? I don't have any hours left to figure it out myself, what with a full-time job and life matters.
Thanks,
Dave
Code:
# New graphics window
# Demo's creating a graphics window
from livewires import games
# initialize graphics screen
games.init(screen_width = 640, screen_height = 480, fps = 50)
# start mainloop
games.screen.mainloop()

You naming your code script pygame.py which rises a conflict with pygame library. Change the name and try it again.

This happens when you try to import from livrewires and in your current working directory there is a script named pygame.py.
Rename the pygame.py script to something else.

Related

"Unknown problem while loading the specified device driver." error in python

I am making a simple program for my entertainment using the playsound module. Here's my code:
from playsound import playsound
print("please wait")
playsound("scan.wav")
and the error messsage:
Traceback (most recent call last):
File "D:\Programi\python\lab\lab.py", line 9, in <module>
playsound("scan.wav")
File "C:\Users\ONT Studios\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\playsound.py", line 35, in _playsoundWin
winCommand('open "' + sound + '" alias', alias)
File "C:\Users\ONT Studios\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\playsound.py", line 31, in winCommand
raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
Error 266 for command:
open "scan.wav" alias playsound_0.98994089730741
Unknown problem while loading the specified device driver.
This is my path: D:\Programi\python\lab with files: lab.py, scan.mp3, and scan.wav.
I tried this, but with no success.
I was facing the same issue today and I was able to fix it in one way. It is probably a bug but you can get around it. So basically when importing several modules in a row, this will create the error. What I did is import first the playsound module then play one sound and print a bunch of random stuff then import the rest of the modules. This fixed my issue.
import mouse
from playsound import playsound
playsound('D:/rakkiz.mp3')
print("\n")
print("\n")
print("\n")
print("\n")
import re
import pywinauto
import time
import keyboard

PyCharm import matplotlib.pyplot show error

import numpy as np
import matplotlib.pyplot as plt
def main():
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
if __name__ == '__main__':
main()
Traceback (most recent call last):
File
"/Users/tim/workspace/Python/MachineLearn/test.py", line 2, in <module>
import matplotlib.pyplot as plt
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 63, in pylab_setup
[backend_name], 0)
File "/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend/backend_interagg.py", line 11, in <module>
from datalore.display import display
File "/Applications/PyCharm.app/Contents/helpers/pycharm_display/datalore/display/__init__.py", line 1, in <module>
from .display_ import *
File "/Applications/PyCharm.app/Contents/helpers/pycharm_display/datalore/display/display_.py", line 5, in <module>
from urllib.parse import urlencode
ImportError: No module named parse
Process finished with exit code 1
=================
Python: 2.7.16
PyCharm Professional: 2019.2
=================
btw, the code run in console mode is work
Simple answer: disable "show plots in scientific window" (Settings -> Tools -> Python Scientific) or downgrade the PyCharm or move your project to python3
Remember to add plt.show() in your code.
A little more complicated. You need to write own importing hooks to find that urllib.parse and urllib.request (next line in display_.py file are requested. More you can read here https://xion.org.pl/2012/05/06/hacking-python-imports/
(i'm not enough familiar with python 2 import system to write it)
For python 2 use
from urlparse import urlparse
If you need to write code which is Python2 and Python3 compatible you can use the following import
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
In your PyCharm project:
press Ctrl+Alt+s to open the settings
on the left column, select Project Interpreter
on the top right there is a list of python binaries found on your system, pick the right one
eventually click the + button to install additional python modules, in your case, it is parse module is missing so install that one
As mentioned by #Grzegorz Bokota, the problem is coming from the "scientific view mode" of PyCharm. This mode allows to visualise graphs and is thus calling matplotlib, and probably an incompatible version of it if you are using Python 2. This bug has been identified here and it seems that we just have to wait for the next release to get it solved.

Python MP3 Player

I Am Trying To Play An MP3 File On Python , But I Can't Find The Right Module!
I've Tried This:
import os
os.startfile('hello.mp3')
But I Just Got The Error:
Traceback (most recent call last):
File "/Applications/Youtube/text 2 speech/test.py", line 2, in <module>
os.startfile('hello.mp3')
AttributeError: 'module' object has no attribute 'startfile'
I Have Also Tried This:
import vlc
p = vlc.MediaPlayer("file:hello.mp3")
p.play()
But I Get The Error:
Traceback (most recent call last):
File "/Applications/Youtube/text 2 speech/test.py", line 1, in <module>
import vlc
ImportError: No module named 'vlc'
But I Still Can't Find The Right Module. Could Someone Please Help?
You will need to install the vlc.py module from https://wiki.videolan.org/Python_bindings
The absolute bare bones for this would be something like:
import vlc
Inst = vlc.Instance()
player = Inst.media_player_new()
Media = Inst.media_new_path('/home/rolf/vp1.mp3')
player.set_media(Media)
player.play()
Although you would need to check player.get_state() to see if it is still running, paused, stopped etc and player.stop() to stop the audio once started
As far as I am aware os.startfile() is only available for the windows operating system.
Using the play command line instruction (Linux and probably OS X)
import os
os.system('play /home/rolf/vp1.mp3')
You could also look at Gstreamer, although the documentation could do with some improvement.
import gst
player = gst.element_factory_make("playbin")
player.set_property("uri", "file:///home/james/vp1.mp3")
player.set_state(gst.STATE_PLAYING)
play is stopped with player.set_state(gst.STATE_NULL),
pause with player.set_state(gst.STATE_PAUSED)
Note: Avoid tutorials for Gstreamer version 0.10, search instead for version 1.0
Both vlc and Gstreamer allow you to play audio and video, although, in my opinion, vlc in simpler to use but Gstreamer is more flexible.
import pygame
from pygame import mixer
def play_music():
global paused
if (paused):
mixer.music.unpause()
paused = False
else:
music = choose_music[0]
mixer.music.load(music)
mixer.music.play()
show_details(music)
musicpage.mainloop()

Curses returning AttributeError: 'module' object has no attribute 'initscr'

I am following the Curses programming HowTo on the Python site, but I am running into a rather bizarre issue.
My code is currently very short, doesn't actually do anything because of this error, I haven't been able to move on. Here's my code:
import curses
#from curses import wrapper
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(True)
def main(stdscr):
begin_x = 20; begin_y = 7
height = 5; width = 40
win = curses.newwin(height, width, begin_y, begin_x)
stdscr.refresh()
stdscr.getkey()
if __name__ == '__main__':
wrapper(main)
and the Traceback:
Traceback (most recent call last):
File "curses.py", line 1, in <module>
import curses
File "/home/nate/Documents/Programming/Python/curses.py", line 4, in <module>
stdscr = curses.initscr()
AttributeError: 'module' object has no attribute 'initscr'
I commented out the from curses import wrapper because that was giving me another error,
Traceback (most recent call last):
File "curses.py", line 1, in <module>
import curses
File "/home/nate/Documents/Programming/Python/curses.py", line 2, in <module>
from curses import wrapper
ImportError: cannot import name wrapper
but I suppose that would be another question.
I am following the tutorial word for word right now, to learn curses, but currently the only thing it's making me do is use curses directed at Python :P.
I am running Python 3.3.2 on Ubuntu 13.10, so this question has nothing to do with this, as he was using Windows and I am not (thankfully :D)
Why am I not able to do this? I'm copying it directly from the Python site, so you'd think it would work!
You named your file curses.py, so Python thinks that file is the curses module. Name it something else.
mv curses.py someOtherName.py
If you get the same error, try removing any .pyc files.
In this case it would be rm curses.pyc.

Python Wildcard Import Vs Named Import

Ok, I have some rather odd behavior in one of my Projects and I'm hoping someone can tell me why. My file structure looks like this:
MainApp.py
res/
__init__.py
elements/
__init__.py
MainFrame.py
Inside of MainFrame.py I've defined a class named RPMWindow which extends wx.Frame.
In MainApp.py this works:
from res.elements.MainFrame import *
And this does not:
from res.elements.MainFrame import RPMWindow
I realize that the wild card import won't hurt anything, but I'm more interested in understanding why the named import is failing when the wild card succeeds.
When using the class name I get this traceback:
Traceback (most recent call last):
File "C:\myApps\eclipse\plugins\org.python.pydev.debug_1.5.6.2010033101\pysrc\pydevd.py", line 953, in <module>
debugger.run(setup['file'], None, None)
File "C:\myApps\eclipse\plugins\org.python.pydev.debug_1.5.6.2010033101\pysrc\pydevd.py", line 780, in run
execfile(file, globals, locals) #execute the script
File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module>
from res.elements.MainFrame import RPMWindow
File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MainFrame.py", line 2, in <module>
from res.elements.MenuBar import MenuBarBuilder
File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MenuBar.py", line 2, in <module>
from MainApp import _, DataCache
File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module>
from res.elements.MainFrame import RPMWindow
ImportError: cannot import name RPMWindow
When using the wild card import I don't receive a traceback and my application opens.
You have circular imports:
MainFrame.py is indirectly importing MainApp.py, and MainApp.py is importing MainFrame.py. As a result, when MainApp.py is importing MainFrame.py, the RPMWindow class hasn't been defined yet and you get the ImportError.
i don't have time to look into why the wildcard is working for you, but what i can say about your failure with the direct name import is that you have an import cycle in your code:
you are trying to import res.elements.MainFrame, but part of that code is trying to import res.elements.MenuBar which tries to import res.elements.MainFrame again. IOW, your first attempt to import res.elements.MainFrame has not completed yet before you try it again.
You have circular imports in your code: the same module is both required by and requires the use of a certain other module, which when you think of it like that, it clearly precarious. Most of the problems can be cleared up by using import a and later referring to a.b instead of from a import b or from a import *.
In particular, never use from a import *. Wildcard imports clutter your namespace and makes your code less maintainable, readable, sane, and predictable. The difference between import a and from a import * is the difference between dragging a box into a room and pouring its contents all over the floor.
It would be better if you could move shared code off to its own module or somehow refactor out the need for a circular import. Circular imports always indicate a design problem.

Categories

Resources