Call current PyMOL session from python script - python-2.7

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

Related

Error ALDialog Python Nao

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

Running script with fixed internal commands arguments to include Qwebengine pepflashplayer

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.

How to launch a Python Spyder session through script / shortcut?

I have this code to launch a Spyder IDE, in Anaconda 2, Python 2.7 :
from spyderlib import start_app
main1= start_app.main()
main1.load_session('/project27/_test01_.session.tar')
'''
from spyderlib.utils.iofuncs import load_session
load_session(filename+'.session.tar')
'''
Code method to load session is here: https://github.com/jromang/spyderlib/blob/master/spyderlib/spyder.py
#---- Sessions
def load_session(self, filename=None):
"""Load session"""
if filename is None:
self.redirect_internalshell_stdio(False)
filename, _selfilter = getopenfilename(self, _("Open session"),
getcwd(), _("Spyder sessions")+" (*.session.tar)")
self.redirect_internalshell_stdio(True)
if not filename:
return
if self.close():
self.next_session_name = filename
the 1st part comes from Anaconda Scripts where Spyder script.
It seems not working to load session.
Spyder sessions were removed in Spyder 3.0. Now the same functionality is provided by Projects (which also save the list of open files in the Editor), so please update to that version.
Besides, Spyder 3.1 will come with a new option called --project to load a project at startup (Spyder 3.1 will be released on January 17/2017).
For people still using only Spyder 2.0 (....), there is a small hack possible to create shortcut of session (SPyder session launched directly with shortcut).
Here, the code :
# -*- coding: utf-8 -*-
import sys, time, os
file_session= ''
if len(sys.argv) > 1 :
file_session= sys.argv[1]
print file_session
sys.argv= sys.argv[:1]
from spyderlib import start_app
if file_session != '' :
main1= start_app.main( file_session)
else :
main1= start_app.main()

Close Python IDLE shell without prompt

I am working on a script (script A), that needs to open a new Python IDLE shell, automatically run another script (script B) in it and then close it. The following code is what I use for this purpose:
import sys
sys.argv=['','-n','-t','My New Shell','-c','execfile("VarLoader.py")']
import idlelib.PyShell
idlelib.PyShell.main()
However I can't get the new shell close automatically. I have tried adding the following to script B but either it doesn't close the new shell or a windows pops up asking whether I want to kill it.
exit()
.
import sys
sys.exit()
Instead of monkeypatching or modifying the IDLE source code to make your program skip the prompt to exit I'd recommend you create a subclass of PyShell that overrides the close method how you want it to work:
import idlelib.PyShell
class PyShell_NoExitPrompt(idlelib.PyShell.PyShell):
def close(self):
"Extend EditorWindow.close(), does not prompt to exit"
## if self.executing:
## response = tkMessageBox.askokcancel(
## "Kill?",
## "Your program is still running!\n Do you want to kill it?",
## default="ok",
## parent=self.text)
## if response is False:
## return "cancel"
self.stop_readline()
self.canceled = True
self.closing = True
return idlelib.PyShell.EditorWindow.close(self)
The original issue with this was that then using idlelib.PyShell.main would not use your subclass, you can in fact create a copy of the function - without modifying the original - by using the FunctionType constructor that will use your modified class:
import functools
from types import FunctionType
def copy_function(f, namespace_override):
"""creates a copy of a function (code, signature, defaults) with a modified global scope"""
namespace = dict(f.__globals__)
namespace.update(namespace_override)
new_f = FunctionType(f.__code__, namespace, f.__name__, f.__defaults__, f.__closure__)
return functools.update_wrapper(f, new_f)
Then you can run your extra IDLE shell like this:
import sys
#there is also a way to prevent the need to override sys.argv but that isn't as concerning to me.
sys.argv = ['','-n','-t','My New Shell','-c','execfile("VarLoader.py")']
hacked_main = copy_function(idlelib.PyShell.main,
{"PyShell":PyShell_NoExitPrompt})
hacked_main()
Now you can leave IDLE the way it is and have your program work the way you want it too. (it is also compatible with other versions of python!)

Apache Django Mod_Wsgi - auto reload

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