I made a PyQt5 QWebengine app i wanna make portable.
I found out that flash weren't working in the app.
After a lot of reading i found out that having pepflashplayer64_*.dll & manifest.json in folder
C:\Windows\System32\Macromed\Flash\ is working.
However i wanna ship the pepflashplayer with app, and
adding custom flash folder to PATH env var, do not have effect , or
sys.path.insert()
the command
myapp.py --ppapi-flash-path=C:\Flash\pepflashplayer64_27_0_0_187.dll
works , but how to pass extra augments internally when script is launched ?
i tried dirty hack to run sys.arg[0] script with extra command but no success.
if __name__ == "__main__":
# print sys.argv
flash = (' --ppapi-flash-path=C:\Flash\pepflashplayer64_27_0_0_187.dll').split()
# print flash
noooo = (sys.argv[0] + flash[0]).split()
import sys
app = QtWidgets.QApplication(noooo)
# ... the rest of your handling: `sys.exit(app.exec_())`, etc.
okay i got it to work so i can make app the app with browser portable , and solution was simpler than i thought.
Parsing second internal argument like this.
if __name__ == "__main__":
programname = os.path.dirname(sys.argv[0]) #get current script full folder path
pepperpflash = ' --ppapi-flash-path=' + programname + '/Flash/pepflashplayer64_27_0_0_187.dll'
try:
app = QtWidgets.QApplication(sys.argv + [pepperpflash])
except:
app = QtWidgets.QApplication(sys.argv)
# ... the rest of your handling: `sys.exit(app.exec_())`, etc.
Related
I have a problem when using the ALDialog module on Python IDE and to load on Nao. I tried in different ways to load a dialogue but I always fall back on the same error.Runtimeerror LoadTopic::ALDialogIncorrect file myDialog.topIn the first case I write directly the text that I save in a. top file but at the time of LoadTopic () I have an error.In the second case I want to load the. top file by giving it the path. I come back to the same mistake again.Do you have a solution to my problem?Thank you very much.
import qi
import argparse
import os
import sys
from naoqi import ALProxy
def main(robot_ip, robot_port):
dialog = """
topic: ~myTopic() \n
language: enu \n
u:(test) hello \n """
file = open("myDialog.top","w")
file.write(dialog)
file.close()
# load topic
proxy = ALProxy("ALDialog",robot_ip,robot_port)
proxy.setLanguage("English")
self.topic = proxy.loadTopic("myDialog.top")
# start dialog
proxy.subscribe("myModule")
# activate dialog
proxy.activateTopic(self.topic)
if name == "main":
parser = argparse.ArgumentParser()
parser.add_argument("--ip", type=str,
default="169.254.245.164",help="Robot's IP address : '169.254.245.164'")
parser.add_argument("--port", type=int, default=9559,help="port number, the default value is OK in most cases")
args = parser.parse_args()
main(args.ip, args.port)
ALDialog.loadTopic expects an absolute filepath on the robot - it doesn't know anything about the context from which you're calling it (it could be from another computer, in which case of course it can't open that file). You need to be sure that your .top is indeed on the robot, and pass it's absolute path to ALDialog.
Once installed on the robot this path will be something like /home/nao/.local/share/PackageManager/apps/your-package-id/your-dialog-name/your-dialog-name_enu.top
Im trying to execute the following code in Python 2.7 on Windows7. The purpose of the code is to take back up from the specified folder to a specified folder as per the naming pattern given.
However, Im not able to get it work. The output has always been 'Backup Failed'.
Please advise on how I get resolve this to get the code working.
Thanks.
Code :
backup_ver1.py
import os
import time
import sys
sys.path.append('C:\Python27\GnuWin32\bin')
source = 'C:\New'
target_dir = 'E:\Backup'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip -qr {0} {1}".format(target,''.join(source))
print('This is a program for backing up files')
print(zip_command)
if os.system(zip_command)==0:
print('Successful backup to', target)
else:
print('Backup FAILED')
See if escaping the \'s helps :-
source = 'C:\\New'
target_dir = 'E:\\Backup'
I'm trying to call current PyMOL session from python script (wxpython GUI), and then load some data from PyMOL and send few commands to PyMOL. At the moment I can open a new PyMOL session in python script:
import sys, os
from wx import *
app = wx.App()
dialog = wx.FileDialog ( None, message = 'Set PyMOL directiry', style = wx.OPEN)
if dialog.ShowModal() == wx.ID_OK:
# Pymol path
moddir = dialog.GetDirectory()
sys.path.insert(0, moddir)
os.environ['PYMOL_PATH'] = moddir
import pymol
pymol.finish_launching()
else:
print 'Nothing was selected.'
from pymol import *
dialog1 = wx.FileDialog ( None, message = 'Set PDB file', style = wx.OPEN)
if dialog1.ShowModal() == wx.ID_OK:
pdbfile = dialog1.GetPath()
cmd.load(pdbfile)
else:
print 'Nothing was selected.'
dialog.Destroy()
app.MainLoop()
BUT actually I'd like to check in my python scrip whether any PyMOL session is already opened.
I found discussion corresponding to this topic here:
Only call function if PyMOL running
Following this discussion I tried to call 'print' function in PyMOL:
try:
from pymol import cmd
print 'Connected'
except:
<open new Pymol sesssion>
but I do not see any text in PyMOL cmd. I tried to determine PyMOL path before this statement and again I failed.
Does anyone know how to call current PyMOL session from python script?
To my knowledge, there is no way to interact with an existing PyMOL session from the Python interpreter. There are a few alternatives:
The existing PyMOL command prompt accepts valid Python and you can run any script directly from the prompt. Perhaps you could execute your script from there instead?
You can start up a new PyMOL session as part of your script. PyMOL's -i flag may be especially helpful- it enables you to work in a headless environment:
-i Disable the internal OpenGL GUI (object list, menus, etc.)
Take a careful look at PyMOL's __init.py__. You'll find the intricacies of PyMOL's threading there. Perhaps you can find something useful to manipulate?
Side note:
Calling print from your script will not make the text appear in the PyMOL session, it will merely write the text to standard output (i.e. it will be printed to your terminal).
The following PyMOL wiki pages may be of help to you:
Running scripts
Launching PyMOL
Launching from a script
I'm working on game project. I use python 2.7.2 for scripting. My application works fine with non unicode path to .exe. But it can't load scripts with unicode path using
boost::python::import (import_path.c_str());
I tried this example
5.3. Pure Embedding http://docs.python.org/extending/embedding.html#embedding-python-in-c
It also can't handle unicode path. I linked python as dll.
Explain me, please, how to handle such path.
boost::python::import needs a std::string, so chances are that import_path misses some characters.
Do you have to work on multiple platform ? On Windows, you could call GetShortPathName to retreive the 8.3 filename and use that to load your dll.
You can make a quick test :
Rename your extension to "JaiDéjàTestéÇaEtJaiDétestéÇa.pyd".
At the command line, type dir /x *.pyd to get the short file name (JAIDJT~1.PYD on my computer)
Use the short name to load your extension.
+The file name above if French for "I already tested this and I didn't like it". It is a rhyme that takes the edge off working with Unicode ;)
This isn't really an answer that will suit your needs, but maybe it will give you something to go on.
I ran into a very similar problem with Python, in my case my application is a pure Python application. I noticed as well that if my application was installed to a directory with a path string that could not be encoded in MBCS (what Python converts to internally for imports, at least Python prior to 3.2 as far as I understand), the Python interpreter would fail, claiming not module of that name existed.
What I had to do was write an Import Hook to trick it into loading those files anyway.
Here's what I came up with:
import imp, os, sys
class UnicodeImporter(object):
def find_module(self,fullname,path=None):
if isinstance(fullname,unicode):
fullname = fullname.replace(u'.',u'\\')
exts = (u'.pyc',u'.pyo',u'.py')
else:
fullname = fullname.replace('.','\\')
exts = ('.pyc','.pyo','.py')
if os.path.exists(fullname) and os.path.isdir(fullname):
return self
for ext in exts:
if os.path.exists(fullname+ext):
return self
def load_module(self,fullname):
if fullname in sys.modules:
return sys.modules[fullname]
else:
sys.modules[fullname] = imp.new_module(fullname)
if isinstance(fullname,unicode):
filename = fullname.replace(u'.',u'\\')
ext = u'.py'
initfile = u'__init__'
else:
filename = fullname.replace('.','\\')
ext = '.py'
initfile = '__init__'
if os.path.exists(filename+ext):
try:
with open(filename+ext,'U') as fp:
mod = imp.load_source(fullname,filename+ext,fp)
sys.modules[fullname] = mod
mod.__loader__ = self
return mod
except:
print 'fail', filename+ext
raise
mod = sys.modules[fullname]
mod.__loader__ = self
mod.__file__ = os.path.join(os.getcwd(),filename)
mod.__path__ = [filename]
#init file
initfile = os.path.join(filename,initfile+ext)
if os.path.exists(initfile):
with open(initfile,'U') as fp:
code = fp.read()
exec code in mod.__dict__
return mod
sys.meta_path = [UnicodeImporter()]
I still run into two issues when using this:
Double clicking on the launcher file (a .pyw file) in windows explorer does not work when the application is installed in a trouble directory. I believe this has to do with how Windows file associations passes the arguments to pythonw.exe (my guess is Windows passes the full path string, which includes the non-encodeable character, as the argument to the exe). If I create a batch file and have the batch file call the Python executable with just the file name of my launcher, and ensure it's launched from the same directory, it launches fine. Again, I'm betting this is because now I can use a relative path as the argument for python.exe, and avoid those trouble characters in the path.
Packaging my application using py2exe, the resulting exe will not run if placed in one of these trouble paths. I think this has to do with the zipimporter module, which unfortunately is a compiled Python module so I cannot easily modify it (I would have to recompile, etc etc).
I am trying to auto reload my django app which uses apache + mod_wsgi on my local windows machine.
I'd like to know where do I add this code that's referenced in the following article:
http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode
def _restart(path):
_queue.put(True)
prefix = 'monitor (pid=%d):' % os.getpid()
print >> sys.stderr, '%s Change detected to \'%s\'.' % (prefix, path)
print >> sys.stderr, '%s Triggering Apache restart.' % prefix
import ctypes
ctypes.windll.libhttpd.ap_signal_parent(1)
Read:
http://blog.dscpl.com.au/2008/12/using-modwsgi-when-developing-django.html
It tells you exactly where to place the file when using Django. You just need to make the code change that everyone is pointing out to you in the source code reloading documentation section related to Windows. Also read:
http://blog.dscpl.com.au/2009/02/source-code-reloading-with-modwsgi-on.html
which explains the variations on the first related to Windows.
You replace the restart function that is mentioned in the block of code above in the same article.
I use this code on my server
touch site.wsgi
and it work. After reload page in browser I get page with changes.
May be it ugly - but simple and no necessary restart apache.
In your Virtual Host config file add this:
WSGIScriptReloading On
And reload Apache
systemctl reload apache2
Enjoy!
Reference https://flask.palletsprojects.com/en/1.1.x/deploying/mod_wsgi/
You replace the restart function in the following block of code you find on the page:
Monitoring For Code Changes
The use of signals to restart a daemon process could also be employed in a mechanism which automatically detects changes to any Python modules or dependent files. This could be achieved by creating a thread at startup which periodically looks to see if file timestamps have changed and trigger a restart if they have.
Example code for such an automatic restart mechanism which is compatible with how mod_wsgi works is shown below.
import os
import sys
import time
import signal
import threading
import atexit
import Queue
_interval = 1.0
_times = {}
_files = []
_running = False
_queue = Queue.Queue()
_lock = threading.Lock()
def _restart(path):
_queue.put(True)
prefix = 'monitor (pid=%d):' % os.getpid()
print >> sys.stderr, '%s Change detected to \'%s\'.' % (prefix, path)
print >> sys.stderr, '%s Triggering process restart.' % prefix
os.kill(os.getpid(), signal.SIGINT)
I test this with Bitnami DjangoStack http://bitnami.org/stack/djangostack and Windows XP installed on D:\BitNami DjangoStack and C:\Documents and Settings\tsurahman\BitNami DjangoStack projects\myproject as project directory (default install)
as in http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode#Restarting_Apache_Processes, I added
MaxRequestsPerChild 1
in file D:\BitNami DjangoStack\apps\django\conf\django.conf
see comment by Graham Dumpleton
then I created a file monitor.py in my project directory with content as in http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode#Monitoring_For_Code_Changes and replace the _restart method with http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode#Restarting_Windows_Apache, here is the part of the script
....
_running = False
_queue = Queue.Queue()
_lock = threading.Lock()
def _restart(path):
_queue.put(True)
prefix = 'monitor (pid=%d):' % os.getpid()
print >> sys.stderr, '%s Change detected to \'%s\'.' % (prefix, path)
print >> sys.stderr, '%s Triggering Apache restart.' % prefix
import ctypes
ctypes.windll.libhttpd.ap_signal_parent(1)
def _modified(path):
try:
....
and in file D:\BitNami DjangoStack\apps\django\scripts\django.wsgi,
....
import django.core.handlers.wsgi
import monitor
monitor.start(interval=1.0)
monitor.track(os.path.join(os.path.dirname(__file__), 'site.cf'))
application = django.core.handlers.wsgi.WSGIHandler()
and then restart the Apache server