How i can disable reopen window on use `set_mrl(...)` function? - libvlc

When i use set_mrl(...) function sometimes the window is reopen i need to keep the window never closed because i used to make share screen automation app.
the note i use python 3.11 with latest libvlc version, and this is my player code
import vlc
import typing as t
import logging
import os
_LOG = logging.getLogger("player.vlc_player")
# https://stackoverflow.com/questions/59377717/how-to-disable-error-messages-output-by-python-vlc-mediaplayer-object
os.environ['VLC_VERBOSE'] = '-1'
class VlcPlayer:
def __init__(self, stream_uri: str) -> None:
self.stream_uri = stream_uri
self.player: vlc.MediaPlayer = vlc.MediaPlayer(stream_uri, "--play-and-pause")
self.player.toggle_fullscreen()
def play(self) -> None:
self.player.play()
def pause(self) -> None:
self.player.pause()
def resume(self) -> None:
self.player.play()
def is_playing(self) -> bool:
return self.player.is_playing()
def get_stream_uri(self) -> str:
return self.stream_uri
def set_stream_uri(self, stream_uri: str) -> None:
self.stream_uri = stream_uri
self.player.set_mrl(stream_uri)
self.player.play()
def get_time(self) -> t.Union[int, t.Any]:
return self.player.get_time()
def set_time(self, time: int) -> None:
self.player.set_time(time)
def get_length(self) -> t.Union[int, t.Any]:
return self.player.get_length()
def get_volume(self) -> t.Union[int, t.Any]:
return self.player.audio_get_volume()
def set_volume(self, volume: int) -> None:
self.player.audio_set_volume(volume)
def stop(self) -> None:
self.player.stop()
also this is my usage
import time
player = VlcPlayer("./images/wating.jpg")
time.sleep(10)
player.set_stream_uri("some url")
time.sleep(1000)
I try set instances to "--play-and-pause" but is not work & i try this solution but not worked with me
win_id = player.get_hwnd()
player.set_hwnd(win_id) # https://stackoverflow.com/questions/65056433/libvlc-keep-window-opened-between-videos

Play is the function that opens a windows if you have not set one already. LibVLC needs a target to draw one. SetMRL does not trigger the opening of a window.

Related

【python】why parent variables address is the same in the child class object

The following is my python code. I think output_ports and input_ports have diffrent address.
class test():
def __init__(self) -> None:
pass
class INode(object):
node_name = "INode"
config = None
output_ports = []
input_ports = []
def __init__(self) -> None:
super().__init__()
pass
def NodeStart(slef):
pass
def GetOutputPort(self):
print(self)
index = len(self.output_ports)
# self.output_ports[index] = test()
self.output_ports.append(test())
# return self.output_ports[index]
def GetInputPort(self):
print(self)
index = len(self.output_ports)
self.input_ports.append(test())
class AdbCollectNode(INode):
def __init__(self) -> None:
super(AdbCollectNode, self).__init__()
self.node_name = "s"
pass
def LinkNode(node_output, node_input):
node_output.GetOutputPort()
node_input.GetInputPort()
if __name__ == '__main__':
adb_node = AdbCollectNode()
adb_node_1 = AdbCollectNode()
adb_node_2 = AdbCollectNode()
LinkNode(adb_node_1, adb_node_2)
LinkNode(adb_node_1, adb_node)
print(id(adb_node_1.input_ports))
print(id(adb_node.input_ports))
print(id(adb_node_2.input_ports))
print(id(adb_node_1.output_ports))
print(id(adb_node.output_ports))
print(id(adb_node_2.output_ports))
id() output as follow:
4549382592
4549382592
4549382592
4549356224
4549356224
4549356224
I think the subclass variables address are the same。 why not same?

My instance variable ID is changing each time I print the instance. The if statement I've written doesn't fix it. Code included

I'm trying to use UUID4 to create an ID for each instance of a class, User, however each time I print the instance a new UUID is generated. I'd thought that the if statement would mean it's only generated once but this isn't the case. Any help/guidance will be much appreciated, thanks.
This is my first time posting so please let me know if i can improve the post or add more info.
class User:
def __init__(self) -> None:
self.user_id = None
self.auth_key = None
if self.user_id == None: self.user_id = uuid4()
def __repr__(self) -> str:
return f"""User ID: {self.user_id}
Authorisation Key: {self.auth_key}"""
new_user = User()
print(new_user)
I've just tried your code without problems. You probably are executing your script many times over and getting different ID's because of that. Each time you run it, new instances will be created by your current Python session and those are totally independent from each other.
from uuid import uuid4
class User:
def __init__(self) -> None:
self.user_id = uuid4()
self.auth_key = None
def __repr__(self) -> str:
return f"User ID: {self.user_id}\nAuthorization Key: {self.auth_key}"
def __eq__(self, other):
return self.user_id == other.user_id
new_user = User()
# Same instance on same session:
print(new_user)
print(new_user)
print(new_user)
# Different instance on same session:
another_user = User()
# Comparing them:
print(f"new_user: {new_user.user_id}")
print(f"another_user: {another_user.user_id}")
# Identity test:
print(f"new_user is new_user: {new_user is new_user}")
print(f"new_user is another_user: {new_user is another_user}")

Python Typing : Create a class function with a generic type, and also access that type through the class

I have a publisher that can publish messages of a certain type:
T = TypeVar('T')
class Publisher(Generic[T]):
def __init__(self, topic: str) -> None:
self.__topic = topic
def publish(self, msg: T):
pass
# As an example, create a publisher that can publish ints
p = Publisher[int]("chatter")
p.publish(1)
This works, and the publish function has the correct type hint, but I want to be able to access the type of the publisher with a get_type() function.
A simple way to do this is to pass the message type into the constructor:
T = TypeVar('T')
class Publisher(Generic[T]):
def __init__(self, msg_type: type, topic: str) -> None:
self.__msg_type = msg_type
self.__topic = topic
def publish(self, msg: T):
pass
def get_type(self) -> type:
return self.__msg_type
p = Publisher[int](int, "chatter")
p.publish(1)
But this requires writing int twice in the line p = Publisher[int](int, "chatter") which seems a bit clumsy and redundant.
I tried wrapping the creation of the publisher in a function so that you don't have to write int twice, but I get a problem:
T = TypeVar('T', bound=type)
class Publisher(Generic[T]):
def __init__(self, msg_type: type, topic: str) -> None:
self.__msg_type = msg_type
self.__topic = topic
def publish(self, msg: T):
pass
def get_type(self) -> type:
return self.__msg_type
def create_publisher(msg_type: T, topic: str) -> Publisher[T]:
return Publisher[T](msg_type, topic)
p = create_publisher(int, "hello")
p.publish(1) #Fails because its expecting Type[int], not an instance of an int
So what I need, is a method to get convert Type[x] into x in a typehint context. Essentially the inverse of what Type does.
e.g, the last example would become:
T = TypeVar('T', bound=type)
class Publisher(Generic[T]):
def __init__(self, msg_type: type, topic: str) -> None:
self.__msg_type = msg_type
self.__topic = topic
def publish(self, msg: InstanceOf[T]):
pass
def get_type(self) -> type:
return self.__msg_type
def create_publisher(msg_type: T, topic: str) -> Publisher[T]:
return Publisher[T](msg_type, topic)
p = create_publisher(int, "hello")
p.publish(1)
But I do not know how to make the InstanceOf generic.
Is there anyway I can do this? Or any other way to get the functionality I want without having to write int twice in the line p = Publisher[int](int, "chatter")
edit
Here is another attempt that also doesn't work, but should clarify what I'm trying to do:
T = TypeVar('T')
class Publisher(Generic[T]):
def __init__(self, topic: str) -> None:
self.__topic = topic
def publish(self, msg: T):
pass
def get_type(self) -> type:
return get_args(Publisher[T])[0]
#This works
print(get_args(Publisher[int])[0])
#This doesn't
p = Publisher[int]("hello")
print(p.get_type())
In this example p.get_type() returns ~T instead of int
Pass in the type explicitly, but annotate it as Type[T]. This allows inference of T without having to specify it, making it enough to specify the type only once (as the argument).
class Publisher(Generic[T]):
# knowing `msg_type` defines `T`
def __init__(self, msg_type: Type[T], topic: str) -> None:
self._msg_type = msg_type
self._topic = topic
def publish(self, msg: T):
pass
def get_type(self) -> Type[T]:
return self._msg_type
# argument of `int` implies T = int
p = Publisher(int, "hello")
print(p.get_type()) # <class 'int'>
if TYPE_CHECKING:
reveal_type(p) # note: Revealed type is 'aaa_testbed.Publisher[builtins.int*]'
I have an answer, based on this answer, but it depends on undocumented implementation details.
from typing import TypeVar, Generic, get_args, get_origin
T = TypeVar('T')
class Publisher(Generic[T]):
def __init__(self, topic: str) -> None:
self.__topic = topic
def publish(self, msg: T):
pass
def get_type(self) -> type:
return get_args(self.__orig_class__)[0]
p = Publisher[int]("hello")
print(p.get_type())

Python Refactoring from Static class?

All over my code I use a python “static” class like this:
curStatus = StaticClass.getStat()
where
class StaticClass:
#staticmethod
def getStat () -> str:
return "noSimulate"
But now I have a refactor issue where sometimes SIMULATE is TRUE or FALSE
SIMULATE: bool = false
If Simulate is true, I want staticmethod.getStat() to be a different method.
But I only want to check SIMULATE once and use polymorphism to do the rest.
& I don’t want to refactor the whole code base.
How can I change StaticClass method by just checking SIMULATE once?
I used this info: python3-patterns
and created these two .py files:
Testing.polymorphism
# https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html
SIMULATE:bool = True
# class myBase(object):
class myBase:
#staticmethod
def factory(sim:bool) :
return yesSim() if sim else myBase()
#staticmethod
def getDroneStatus() -> str:
print("myBase.getDroneStatus()")
return "UNITIALIZED! FAIL!!"
#staticmethod
def getStaticStatus() -> str:
print("myBase.getStaticStatus()")
return "UNITIALIZED! FAIL!!"
class yesSim(myBase):
#staticmethod
def getDroneStatus() -> str:
return "yesSim"
GSCRAMtcp = myBase.factory(SIMULATE)
if __name__ == '__main__':
myTCP = myBase.factory(SIMULATE)
print(myTCP.getStaticStatus())
print(myTCP.getDroneStatus())
and this testfile:
from Testing.polymorphism.testPolymorph import GSCRAMtcp
if __name__ == '__main__':
print(GSCRAMtcp.getDroneStatus())
print(GSCRAMtcp.getStaticStatus())

PyQt5 [Windows 8- Python 3.2]: QPushButton clicked slot not getting called

Below is a code to select files using a dialog box with progress bar, log viewer and close button. Have registered the close button with a test call back slot. But while executing this code, slot function is not getting called.
Can someone point out the program in this code?
from lib import window, widgets
from PyQt5.QtCore import pyqtSlot
class FileUploader:
def __init__ (self, windowObj):
self.progressBar = None
self.logViewer = None
self.closeButton = None
self.filePercent = 100
self.totalPercent = 0
self.fileSelectDialog = None
self.__createWidgets (windowObj)
return
def __createWidgets (self, windowObj):
vboxObj = widgets.VBox ()
hboxObj = widgets.HBox ()
self.progressBar = widgets.ProgressBar (parent=windowObj)
self.logViewer = widgets.TextEdit (parent=windowObj)
self.closeButton = widgets.PushButton ('&Close', parent=windowObj)
hboxObj.addWidget (self.progressBar)
hboxObj.addWidget (self.closeButton)
vboxObj.insertLayout (0, hboxObj)
vboxObj.addWidget (self.logViewer)
windowObj.setLayout (vboxObj)
(self.closeButton).clicked.connect (self.test)
return
def acceptInputFiles (self, winTitle, fileFilters, windowObj):
(self.progressBar).setRange (0,100)
(self.progressBar).setValue (0)
self.fileSelectDialog = window.FileDialog (title=winTitle, filter=fileFilters, parent=windowObj)
selectedFiles = (self.fileSelectDialog).getSelectedFiles ()
if len(selectedFiles) == 0:
(self.logViewer).append ('No Files to process')
return selectedFiles
#pyqtSlot()
def test (self):
print ('clicked')

Resources