I have a program written by PyQt that plays video by binding libvlc.
# -*- coding: utf-8 -*-
import sys
import os
import vlc
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
class vlc_demo(QWidget):
def __init__(self):
super(vlc_demo, self).__init__()
self.__ui__()
self.__load__()
def __ui__(self):
self.setFixedSize(800,600)
t_lay_parent = QVBoxLayout()
self.m_label_media = QLabel()
t_lay_bottom = QHBoxLayout()
self.m_button_one = QPushButton("one")
self.m_button_too = QPushButton("too")
self.m_button_three = QPushButton("three")
t_lay_bottom.addWidget(self.m_button_one)
t_lay_bottom.addWidget(self.m_button_too)
t_lay_bottom.addWidget(self.m_button_three)
self.m_button_one.clicked.connect(self.slt_one)
self.m_button_too.clicked.connect(self.slt_too)
self.m_button_three.clicked.connect(self.slt_three)
t_lay_parent.addWidget(self.m_label_media)
t_lay_parent.addLayout(t_lay_bottom)
self.setLayout(t_lay_parent)
def __load__(self):
self.m_instance = vlc.Instance()
self.m_player = self.m_instance.media_player_new()
self.m_win_id = self.m_label_media.winId()
if sys.platform.startswith('linux'): # linux
self.m_player.set_xwindow(self.m_win_id)
elif sys.platform == "win32": # windows
self.m_player.set_hwnd(self.m_win_id)
elif sys.platform == "darwin": # mac
self.m_player.set_nsobject(self.m_win_id)
def slt_one(self):
self.m_label_media.show()
media = self.m_instance.media_new("1.mp4")
self.m_player.set_media(media)
self.m_player.play()
def slt_too(self):
self.m_label_media.show()
media = self.m_instance.media_new("2.mp4")
self.m_player.set_media(media)
self.m_player.play()
def slt_three(self):
self.m_label_media.hide()
if __name__ == "__main__":
app = QApplication(sys.argv)
win = vlc_demo()
win.show()
sys.exit(app.exec_())
Under windows, copy the following files and directories in the VLC media player directory. The program can run on the machine without VLC media player.
- libvlc.dll
- libvlccore.dll
- plugins
Under CentOS7, is there any way to run the program without installing VLC media player?
I believe you may use Snapcraft Parts which AFAIU is designed for just that.
For VLC that's https://github.com/videolan/vlc/blob/master/extras/package/snap/snapcraft.yaml
Related
I'm trying to write a function that tests activation email send by selenium Firefox client.
Activation Emails are successfully written as files under "tests/test_selenium/outbox" directory, but I"m not able to handle email in test_activation_mail() method.
Django==2.2
pytest-django==3.8.0
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = os.path.join(BASE_DIR, "tests", "test_selenium", "outbox")
test_registration.py
import pytest, time, os
from django.core import mail
from src import settings
from yaml import safe_load
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# firefox driver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
#pytest.mark.django_db(transaction=True)
class TestCreateAccount():
t_username = "Pesho"
t_password = "alabala"
t_perm_email_1 = "pesho#example.com"
t_perm_email_2 = "pesho#example.com"
t_denied_email = "pesho#gmail.com"
def setup_method(self, method):
# Load config and check/download browser driver
config_file = 'tests/test_selenium/selenium_config.yml'
with open(config_file) as ymlfile:
cfg = safe_load(ymlfile)
# Firefox headless option
options = Options()
if cfg['HEADLESS_BROWSER']:
options.headless=True
if cfg['BROWSER'].lower() == 'firefox':
# check if driver is downloaded
try:
if os.path.isfile(cfg['SELENIUM_DRIVER_FF_BIN']):
print(f"Driver {cfg['SELENIUM_DRIVER_FF_BIN']} found")
except Exception as e:
raise(f'Driver not found: {e} run selenium_downloader.py first')
self.driver = webdriver.Firefox(
options=options,
# firefox_profile = ff_profile,
# capabilities=firefox_capabilities,
# firefox_binary=binary,
executable_path=cfg['SELENIUM_DRIVER_FF_BIN'])
elif cfg['BROWSER'].lower() == 'chrome':
raise NotImplementedError
def teardown_method(self, method):
# time.sleep(120)
self.driver.quit()
def test_activation_mail(self):
mail.outbox = []
m = mail.get_connection(backend=settings.EMAIL_BACKEND)
self.driver.get("http://127.0.0.1:8000/accounts/login/?next=/")
self.driver.set_window_size(1024, 768)
self.driver.find_element(By.LINK_TEXT, "Register").click()
self.driver.find_element(By.ID, "id_username").click()
self.driver.find_element(By.ID, "id_username").send_keys(self.t_username)
self.driver.find_element(By.ID, "id_email").send_keys(self.t_perm_email_1)
self.driver.find_element(By.ID, "id_password1").send_keys(self.t_password)
self.driver.find_element(By.ID, "id_password2").send_keys(self.t_password)
self.driver.find_element(By.ID, "id_password2").send_keys(Keys.ENTER)
alert_success = WebDriverWait(self.driver, 4).until(
EC.presence_of_element_located((By.CSS_SELECTOR, ".alert")))
if alert_success.text == f"New account created for {self.t_username}, Please check your email and confirm registration.":
# print(f'File name: {m._fname}')
email = mail.outbox[0]
assert len(mail.outbox) == 1
Running that test with:
pkill -f geckodriver ; sleep 3 ; pytest -v --ds=src.settings --pdb --pdbcls=IPython.terminal.debugger:Pdb tests/tests_selenium/test_registration.py::TestCreateAccount::test_activation_mail
Ends with Error :
E IndexError: list index out of range
because of the empty mail.outbox
What do I miss here ?
I am new in python. I want to update an image on label1. But function 'def browse' always give me blank label instead. Seems the code does not get the image or it failed to update the label, and the program did not give any error message. Did i missed something here? Also, print command below setPixmap command is executed. i am using python 2.7 and PyQT4.
Thanks in advance
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import os, sys
import cv2
from PIL.ImageQt import ImageQt
class GuiCakep(QtGui.QWidget):
global label1, label2
def __init__(self):
super(GuiCakep, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 1000, 600)
self.setWindowTitle('Single Browse')
self.label1 = QtGui.QLabel(self)
self.label1.setFrameShape(QtGui.QFrame.Box)
self.label1.setGeometry(QtCore.QRect(20, 10, 451, 451))
pixmap = QPixmap('1stimage.jpg')
self.label1.setPixmap(pixmap)
self.label2 =QtGui.QLabel(self)
self.label2.setFrameShape(QtGui.QFrame.Box)
self.label2.setGeometry(QtCore.QRect(481, 10, 451, 451))
btn = QtGui.QPushButton('Browse', self)
btn.resize(btn.sizeHint())
btn.clicked.connect(self.browse)
btn.move(775, 500)
self.show()
def browse(self):
filePath = QtGui.QFileDialog.getOpenFileName(self, 'a file','*.jpg')
fileHandle = open(filePath, 'r')
pixmap = QPixmap('filePath')
self.label1.setPixmap(pixmap)
print("Whoa awesome")
def main():
app = QtGui.QApplication(sys.argv)
w = GuiCakep()
app.exec_()
if __name__ == '__main__':
main()
You are creating a Pixmap with 'filePath' as argument. This is a string, not your variable filePath.
Remove the both ' and this should update the label.
I am trying to make a simple maths quiz game that shows Numbers and when I press space it shows the result , the Application launch with a QTdyalog GUI first and after I finish configuring the gameplay a Kivy screen should show up and the game starts until the user press escape it gets back to the config GUI
here is the Programm skeleton
import kivy
from kivy.app import App
from kivy.uix.label import Label
import sys
from PyQt4 import QtCore, QtGui, uic
qtCreatorFile = "ConfigForm.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class Playy(App): #the Kivy app
def build(self):
l = Label(text='Hello world')
return l
class Conf(QtGui.QDialog, Ui_MainWindow): #the COnfiguration Gui
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.buttonBox.accepted.connect(self.oky)
self.buttonBox.rejected.connect(self.notok)
def oky(self):
print "OK OK OK OK" #creating a Kivy app instance and running it
ins = Playy()
ins.run()
def notok(self):
print "cancel cancel"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = Conf()
window.show()
sys.exit(app.exec_())
I am only having Issue with making functions inside the Kivy app class and passing arguments Into them and also handling Objects properties such as label text this is my first Kivy experiment tell me what do you think
i've an issue with my code, may be one of you will be able to help me about this
here is my script.py :
#! /usr/bin/python
# -*- coding:utf-8 -*-
import jinja2.ext
import webbrowser
def main():
from flask import Flask, flash, redirect, render_template, \
request, url_for,escape, session
from flask_bootstrap import Bootstrap
app = Flask(__name__)
webbrowser.open_new_tab('http://127.0.0.1:5000')
Bootstrap(app)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/choice')
def choice():
return render_template('Choice.html')
#app.route('/src&dest')
def GenerationPage():
return render_template('generate.html')
#app.route('/success')
def successfull():
return render_template('success.html')
return app.run(debug=True)
if __name__ == "__main__":
main()
and my setup.py :
import sys
import os
from cx_Freeze import setup,Executable
path = sys.path + ["src", "src/templates"]
includes = [sys, os]
excludes = []
packages = []
include_files = ['templates']
options = {"path": path,
"includes": includes,
"excludes": excludes,
"include_files": include_files
}
if sys.platform == "win32":
options["include_msvcr"] = True
base = None
if sys.platform == "win32":
base = "Win32GUI"
FirstTarget = Executable(
script="Other.py",
base=base,
compress=False,
copyDependentFiles=True,
appendScriptToExe=True,
appendScriptToLibrary=False
)
setup(
name="FlaskTrapeze",
version="0.1",
description="Ouvre une interface web",
author="Axel M",
options={"build_exe": options},
executables=[FirstTarget]
)
I'm facing this issue when I try to build it under windows
"AttributeError: 'module' object has no attribute 'rfind'"
Thanks for the help !
I have a simple chat application in Tornado powered with RethinkDB.
Am trying to integrate this tornado chat application to run with django site.
For that reason, I have adopted below in rechat.py in order for it to work with django.
Namespaces tornado.wsgi and django.core.wsgi (get_wsgi_application)
Set environment variable for Django settings.py
os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoapp.settings'
When I try to run it after the above changes, it connects the db server, but doesn't do anything. What am I missing?
How can I make this tornado app to work with django 1.8 site?
Below is my code of rechat.py (https://github.com/v3ss0n/rechat) -
import logging
import tornado.escape
from tornado.ioloop import IOLoop
import tornado.web
import os.path
import rethinkdb as r
from tornado import httpserver
from time import time
# from tornado.concurrent import Future
from tornado import gen
from tornado.options import define, options, parse_command_line
import tornado.wsgi
from django.core.wsgi import get_wsgi_application
define("port", default=8888, help="run on the given port", type=int)
define("debug", default=True, help="run in debug mode")
def setup_db(db_name="rechat", tables=['events']):
connection = r.connect(host="localhost")
try:
r.db_create(db_name).run(connection)
for tbl in tables:
r.db(db_name).table_create(tbl, durability="hard").run(connection)
logging.info('Database setup completed.')
except r.RqlRuntimeError:
logging.warn('Database/Table already exists.')
finally:
connection.close()
class RechatApp(tornado.web.Application):
def __init__(self, db):
handlers = [
(r"/", MainHandler),
(r"/a/message/new", MessageNewHandler),
(r"/a/message/updates", MessageUpdatesHandler),
]
settings = dict(cookie_secret="_asdfasdaasdfasfas",
template_path=os.path.join(
os.path.dirname(__file__), "templates"),
static_path=os.path.join(
os.path.dirname(__file__), "static"),
xsrf_cookies=True,
debug=options.debug)
self.db = db
logging.info(db)
tornado.web.Application.__init__(self, handlers, **settings)
class BaseHandler(tornado.web.RequestHandler):
def initialize(self):
self.db = self.application.db
self.evt = r.table("events")
class MainHandler(BaseHandler):
#gen.coroutine
def get(self):
curs = yield self.evt.run(self.db)
messages = []
while (yield curs.fetch_next()):
item = yield curs.next()
messages.append(item)
self.render("index.html", messages=messages)
class MessageNewHandler(BaseHandler):
#gen.coroutine
def post(self):
message = {
"body": self.get_argument("body")
}
# to_basestring is necessary for Python 3's json encoder,
# which doesn't accept byte strings.
start = time()
messages = (yield self.evt.insert(message).run(self.db))
time_taken = time() - start
logging.warn("DBINSERT: %s seconds" % time_taken)
message['id'] = messages['generated_keys'][0]
message["html"] = tornado.escape.to_basestring(
self.render_string("message.html", message=message))
if self.get_argument("next", None):
self.redirect(self.get_argument("next"))
else:
self.write(message)
class MessageUpdatesHandler(BaseHandler):
#gen.coroutine
def post(self):
curs = yield self.evt.changes().run(self.db)
while (yield curs.fetch_next()):
feed = yield curs.next()
message = {
'id': feed['new_val']['id'],
'html': tornado.escape.to_basestring(
self.render_string("message.html",
message=feed['new_val']))}
break
self.finish(dict(messages=[message]))
#gen.coroutine
def main():
""" Async main method. It needed to be async due to r.connect is async . """
parse_command_line()
os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoapp.settings'
db_name = "rechat"
setup_db(db_name)
r.set_loop_type("tornado")
db = yield r.connect("localhost", db=db_name)
#Single db connection for everything thanks a lot Ben and Jeese
http_server = httpserver.HTTPServer(RechatApp(db))
http_server.listen(options.port)
if __name__ == "__main__":
IOLoop.current().run_sync(main)
IOLoop.current().start()