I wanted to build a program which streams radio from address. I wrote the following code:
try:
from gi.repository import Gst
except AttributeError as e:
pass
def on_tag(bus, msg):
taglist = msg.parse_tag()
print 'on_tag:'
for key in taglist.keys():
print '\t%s = %s' % (key, taglist[key])
music_stream_uri = 'http://213.8.143.168/91fmAudio'
player = Gst.element_factory_make("playbin", "player")
player.set_property('uri', music_stream_uri)
player.set_state(Gst.STATE_PLAYING)
It worked well when I did
import pygst
pygst.require("0.10")
import gst
but since It gave me several AttributeError and warning claims the module is deprecating I switched to pyGi and imported
from pi.repository import Gst
but then I got the error
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.1\helpers\pydev\pydevd.py", line 2222, in <module>
globals = debugger.run(setup['file'], None, None)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.1\helpers\pydev\pydevd.py", line 1648, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:/Danis/radio/radio.py", line 20, in <module>
player = Gst.element_factory_make("playbin", "player")
File "C:\Python27\lib\site-packages\gi\module.py", line 320, in __getattr__
return getattr(self._introspection_module, name)
File "C:\Python27\lib\site-packages\gi\module.py", line 139, in __getattr__
self.__name__, name))
AttributeError: 'gi.repository.Gst' object has no attribute 'element_factory_make'
I wonder which command in pi.Gst is equivalent to the commands of the pygst? Does anybody know how to transfer this piece of code to PyGi?
I recommend you install an interpreter with tab completion such as ipython to look up methods. You will find documentation for introspected libs in python at http://lazka.github.io/pgi-docs/
Regarding your specific problem, the call to make is Gst.ElementFactory.make ()
Cheers!
Related
I am making a program that will allow my phone to share its clipboard with my PC. I am using Pyperclip as it appears to be the easiest and most cross-platform solution. However, when I run the code below:
...
elif "incoming_clipboard:" in server_command:
print(server_command)
pyperclip.copy(server_command.replace("incoming_clipboard: ", ""))
...
I get the error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/usr/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "/home/chris/Documents/Programming/Synchrony/Desktop/Phone.py", line 30, in do_sync
self.handle_commands(bluetooth_socket)
File "/home/chris/Documents/Programming/Synchrony/Desktop/Phone.py", line 65, in handle_commands
pyperclip.copy(server_command.replace("incoming_clipboard: ", ""))
File "/usr/lib/python3.9/site-packages/pyperclip/__init__.py", line 659, in lazy_load_stub_copy
return copy(text)
File "/usr/lib/python3.9/site-packages/pyperclip/__init__.py", line 158, in copy_gtk
cb = gtk.Clipboard()
File "/usr/lib/python3.9/site-packages/gi/__init__.py", line 69, in __getattr__
raise AttributeError(_static_binding_error)
AttributeError: When using gi.repository you must not import static modules like "gobject". Please change all occurrences of "import gobject" to "from gi.repository import GObject". See: https://bugzilla.gnome.org/show_bug.cgi?id=709183
I know its not due to the string being invalid or anything, because 1) I am explicitly converting it from bytes to a string, and 2) it prints perfectly fine. I don't know if this is relevant, but I am using Linux, so perhaps that is affecting Pyperclip?
Do you guys have any solutions?
https://github.com/dynobo/normcap/issues/100
After going to the Github page for PyperClip, I found a similar issue that someone else had that suggested switching to PyClip. After installing PyClip and implementing it in project, I can confirm that it works perfectly without any issues.
I'm having a hard time handling Exceptions in pycharm 3.8:
When I press ctrl+c running my program, it doesn't work, so I've been told to use pycharm console to test it, and it does work, interrupting the keyboard input.
def readFloat(msg):
while True:
try:
return float(input(f'{msg}'))
except (ValueError, TypeError):
print(f'\033[31mError. Not valid.\033[m')
continue
except KeyboardInterrupt:
print('\033[31mYou didn\'t type a number.\033[m')
return 0
b = readFloat('Your Number: ')
print(f'\nThat\'s your number: {b}')
But now, when I try to Control+C, it doesn't catch my except and print my custom error report, returning 0. It gives me some huge and red error lines:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/User/PycharmProjects/Curso/Aula 23/ex113.py", line 35, in <module>
b = readFloat('Your Number: ')
File "C:/Users/User/PycharmProjects/Curso/Aula 23/ex113.py", line 26, in readFloat
return float(input(f'{msg}'))
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_stdin.py", line 64, in readline
requested_input = self.rpc_client.requestInput()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_comm\pydev_transport.py", line 226, in _req
return super(TSyncClient, self)._req(_api, *args, **kwargs)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\third_party\thriftpy\_shaded_thriftpy\thrift.py", line 160, in _req
return self._recv(_api)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\third_party\thriftpy\_shaded_thriftpy\thrift.py", line 192, in _recv
raise v
console_thrift.KeyboardInterruptException: KeyboardInterruptException()
So I tried to add a generic exception just to print the error class, and I got this:
Error found: <class 'console_thrift.KeyboardInterruptException'>
So I can't manage to detect an except keyboardInterrupt and work with it, just using a generic exception, any ideas?
Edit
The only plugin that I added was a Theme UI to run pycharm totally black, the rest of them came with the instalation, I think. I ran the .py file using CMD and it works just fine, detecting the keyboard interrupt.
Try this:
try:
from console_thrift import KeyboardInterruptException as KeyboardInterrupt
except ImportError:
pass
Ref: Why doesn't this python keyboard interrupt work? (in pycharm)
The thing about IDEs is that they are not quite the same as running normally, especially when it comes to handling of keyboard characters. The way you press ctrl-c, your IDE thinks you want to copy text. The python program never sees the character. Perhaps it brings up a separate window when running? Then you would select that window before ctrl-c.
I am using OpenGL to render a scene in python. My code works perfectly fine on windows but, for some reason, I'm having issues when importing opengl.gl on MacOS.
The issue arises when calling from OpenGL.GL import ... in both python scripts and the python console.
More specifically here is the exact call in my script:
from OpenGL.GL import glGenBuffers, glBindBuffer, glBufferData, \
glGenVertexArrays, glBindVertexArray, glEnableVertexAttribArray, glVertexAttribPointer, \
glDrawArrays, glUseProgram, glEnable, glDisable, \
GL_ARRAY_BUFFER, GL_STATIC_DRAW, GL_DEPTH_TEST, \
GL_FLOAT, GL_FALSE, \
GL_TRIANGLES, GL_LINES, GL_LINE_STRIP
This results in the following error:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/darwin.py", line 35, in GL
return ctypesloader.loadLibrary(
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/ctypesloader.py", line 36, in loadLibrary
return _loadLibraryWindows(dllType, name, mode)
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/ctypesloader.py", line 89, in _loadLibraryWindows
return dllType( name, mode )
File "/usr/local/Cellar/python#3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ctypes/__init__.py", line 373, in __init__
self._handle = _dlopen(self._name, mode)
OSError: ('dlopen(OpenGL, 10): image not found', 'OpenGL', None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/iyadboustany/Desktop/lensmaster/Lensmaster.py", line 18, in <module>
from MainWindow import MainWindow
File "/Users/iyadboustany/Desktop/lensmaster/MainWindow.py", line 14, in <module>
from Robot import Robot
File "/Users/iyadboustany/Desktop/lensmaster/Robot.py", line 8, in <module>
from Graphics.Scene import DHNode
File "/Users/iyadboustany/Desktop/lensmaster/Graphics/Scene.py", line 13, in <module>
from OpenGL.GL import glGenBuffers, glBindBuffer, glBufferData, \
File "/usr/local/lib/python3.8/site-packages/OpenGL/GL/__init__.py", line 3, in <module>
from OpenGL import error as _error
File "/usr/local/lib/python3.8/site-packages/OpenGL/error.py", line 12, in <module>
from OpenGL import platform, _configflags
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/__init__.py", line 36, in <module>
_load()
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/__init__.py", line 33, in _load
plugin.install(globals())
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 97, in install
namespace[ name ] = getattr(self,name,None)
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 15, in __get__
value = self.fget( obj )
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/darwin.py", line 62, in GetCurrentContext
return self.CGL.CGLGetCurrentContext
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 15, in __get__
value = self.fget( obj )
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/darwin.py", line 45, in CGL
def CGL(self): return self.GL
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 15, in __get__
value = self.fget( obj )
File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/darwin.py", line 41, in GL
raise ImportError("Unable to load OpenGL library", *err.args)
ImportError: ('Unable to load OpenGL library', 'dlopen(OpenGL, 10): image not found', 'OpenGL', None)
Notes:
Running glxgears works just fine.
I'm running macOS Big Sur beta (20A5343i)
I'm using python 3.8.5
I installed opengl using pip: pip3 install PyOpenGL PyOpenGL_accelerate
This error is because Big Sur no longer has the OpenGL library nor other system libraries in standard locations in the file system and instead uses a cache. PyOpenGL uses ctypes to try to locate the OpenGL library and it fails to find it. Fixing ctypes in Python so that it will find the library is the subject of this pull request
https://github.com/python/cpython/pull/21241
So a future version of Python should resolve the problem.
To fix it now you can edit PyOpenGL file OpenGL/platform/ctypesloader.py changing line
fullName = util.find_library( name )
to
fullName = '/System/Library/Frameworks/OpenGL.framework/OpenGL'
Since I hate the idea of patching a Python package (plus it is really hard to manage that with use of Conda to install said package), I offer this kludge as a workaround for until Python gets its Big Sur (aka Big Nuisance) update:
try:
import OpenGL as ogl
try:
import OpenGL.GL # this fails in <=2020 versions of Python on OS X 11.x
except ImportError:
print('Drat, patching for Big Sur')
from ctypes import util
orig_util_find_library = util.find_library
def new_util_find_library( name ):
res = orig_util_find_library( name )
if res: return res
return '/System/Library/Frameworks/'+name+'.framework/'+name
util.find_library = new_util_find_library
except ImportError:
pass
It's better to change this to
fullName = "/System/Library/Frameworks/{}.framework/{}".format(name,name)
otherwise GLUT won't work. At least, this let me run the Cozmo SDK's 3d stuff again.
FYI, in my case it was:
fullName = '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/OpenGL.framework/OpenGL'
None of these are really very suitable answers - there were several issues with both MacOS and pyOpenGL.
Fortunately, however - everything seems to be working at last if we upgrade to Python3.10 (or above)
I'm encountering a weird error when running the script in PyCharm's debug mode or inside a Flask app. I have narrowed down my code to the following
import virtualbox
import threading
class ThreadExecutor(threading.Thread):
def __init__(self):
super().__init__()
def run(self):
vbox = virtualbox.VirtualBox()
if __name__ == '__main__':
th = ThreadExecutor()
th.start()
Running this as a module produces no errors and executes perfectly fine but in debug mode it produces the following error message
Connected to pydev debugger (build 181.5087.37)
Exception in thread Thread-6:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\site-packages\vboxapi\__init__.py", line 449, in __init__
None)
pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:/Users/.../dev/debug.py", line 13, in run
vbox = virtualbox.VirtualBox()
File "C:\Program Files\Python36\lib\site-packages\virtualbox\library_ext\vbox.py", line 22, in __init__
manager = virtualbox.Manager()
File "C:\Program Files\Python36\lib\site-packages\virtualbox\__init__.py", line 143, in __init__
self.manager = vboxapi.VirtualBoxManager(mtype, mparams)
File "C:\Program Files\Python36\lib\site-packages\vboxapi\__init__.py", line 991, in __init__
self.platform = PlatformMSCOM(dPlatformParams)
File "C:\Program Files\Python36\lib\site-packages\vboxapi\__init__.py", line 455, in __init__
print("Warning: CoInitializeSecurity failed: ", oXctp);
NameError: name 'oXctp' is not defined
Going into \vboxapi__init__.py we find
try:
pythoncom.CoInitializeSecurity(None,
None,
None,
pythoncom.RPC_C_AUTHN_LEVEL_DEFAULT,
pythoncom.RPC_C_IMP_LEVEL_IMPERSONATE,
None,
pythoncom.EOAC_NONE,
None)
except:
_, oXcpt, _ = sys.exc_info();
if isinstance(oXcpt, pythoncom.com_error) and self.xcptGetStatus(oXcpt) == -2147417831: # RPC_E_TOO_LATE
print("Warning: CoInitializeSecurity was already called");
else:
print("Warning: CoInitializeSecurity failed: ", oXctp);
What's causing this error? Does sys.exc_info() behave differently inside a thread inside a debugger?
There seems to be some known, unresolved issues in the interaction between threading and virtualbox, see here. I would suggest using multiprocessing instead as I have not experienced any of the previous issues with it.
The release notes for libarchive state that because of an older version of libarchive being included within MacOS they recommend changing LD_LIBRARY_PATH to point towards the location of the recent copy of libarchive.
I've used this code to try and achieve that but I get an error message when I run the script.
import os
print os.environ.get('LD_LIBRARY_PATH') #Check what the current path is
os.environ['LD_LIBRARY_PATH'] = '/Library/Python/2.7/site-packages/'
print os.environ.get('LD_LIBRARY_PATH') #Check the variable has been set
import libarchive.public
Error:
None
/Library/Python/2.7/site-packages/
Traceback (most recent call last):
File "scratch.py", line 8, in <module>
import libarchive.public
File "/Library/Python/2.7/site-packages/libarchive/public.py", line 1, in <module>
from libarchive.adapters.archive_read import \
File "/Library/Python/2.7/site-packages/libarchive/adapters/archive_read.py", line 7, in <module>
import libarchive.calls.archive_read
File "/Library/Python/2.7/site-packages/libarchive/calls/archive_read.py", line 17, in <module>
c_archive_read_support_filter_all = libarchive.archive_read_support_filter_all
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 378, in __getattr__
func = self.__getitem__(name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 383, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: dlsym(0x7fb08b741000, archive_read_support_filter_all): symbol not found
I cant find a great answer to this anywhere out there.
It is not clear from the tool documentation, but based on a thread: https://github.com/dsoprea/PyEasyArchive/issues/16 I set another environment variable to the place where the underlying c library could be found. In my case, it was put there by homebrew on my mac.
os.environ['LA_LIBRARY_FILEPATH']='/usr/local/opt/libarchive/lib/libarchive.dylib'
import libarchive.public
worked for me.