Pyomo closes Excel - python

Whenever I run a python script from cmd prompt containing the following
from pyomo.environ import *
any open instance of excel closes. I have no idea why this is happening? Any help would be great. Thanks

This appears to be a bug with how Pyomo (really PyUtilib) interacts with Excel on Windows (see https://github.com/Pyomo/pyomo/issues/355). If you plan to use Pyomo with Excel, there really isn't a workaround. If you are OK with disabling support for Pyomo's excel-specific data import mechanisms, then you can work around this bug by editing pyomo/core/plugins/data/sheet.py and disabling the following code:
if win32com_available:
from pyutilib.excel.spreadsheet_win32com import ExcelSpreadsheet_win32com
tmp = ExcelSpreadsheet_win32com()
try:
tmp._excel_dispatch()
tmp._excel_quit()
_excel_available = True
except:
pass
(The simplest thing to do is change if win32com_available: to if False:)

Related

Python break the command line, why?

I just want to launch my program written in C++ from a Python script.
I wrote the following script:
import subprocess
subprocess.call(['l:\Proj\Silium.exe', '--AddWatch c:\fff.txt'])
But to my c++ application the parameter "--AddWatch c:\fff.txt" arrives without hyphens - it arrives as "AddWatch c:\fff.txt". So my program doesn't work.
Why does this happen, and how can I fix it?
UPD: thx for comments - yours answer helps!
I explain the issue and the solution.
I need to launch my application in the following way:
l:\Proj\Silium.exe --AddWatch c:\fff.txt
When I tried to do this using some hint from internet:
import subprocess
subprocess.call(['l:\Proj\Silium.exe', '--AddWatch c:\fff.txt'])
the key "--AddWatch" arrives to my program without hyphens - like "AddWatch".
The solution is quite simple:
import subprocess
subprocess.call(['l:\Proj\Silium.exe', '--AddCMakeWatch', 'c:\fff.txt',])
And issue gone away.
P.S.: its very strange that my initial code didnt work, I dont have any idea why python corrupt the command line, I think it is the python bug.

Getting rid of black console windows when running sympy through spyder

Whenever I try to display symbolic math in Spyder via the IPython console, several black console windows pop up and then disappear in quick succession. It prints the expression, but I'd like to know if there is a way to get rid of these windows. The windows have the title "C:\Program Files\MikTex 2.9..." if that helps.
It looks like someone already figured it out and posted a solution on GitHub. This is the link: https://github.com/sympy/sympy/issues/11882
It took me (as a novice) some time to figure out exactly what he did, so the following is just a more detailed explanation:
You first need to find the compatibility module in the sympy package. For me, it was located at "C:\Users\Lucas\Anaconda3\Lib\site-packages\sympy\core\compatibility.py". Next, you need to search (in the source code of that module) for the check_output function. The surrounding code should look something like:
# check_output() is new in Python 2.7
import os
try:
try:
from subprocess import check_output
Finally, you need to get rid of the last line, and replace it with the code found in the GitHub link. The resulting block should look like:
# check_output() is new in Python 2.7
import os
try:
try:
from subprocess import check_output as subprocess_check_output
def check_output(*args, **kwargs):
return subprocess_check_output(*args, **kwargs, creationflags=0x08000000) # CREATE_NO_WINDOW
It appears to me that he defines a function which takes the place of check_output, except that the argument to suppress the output windows is always fed in. Hope this helps anyone else having this problem, and I appreciate the fix from Adam on GitHub.
I submitted a pull request to fix this for good:
https://github.com/sympy/sympy/pull/12391

Making a GDB debugging helper for the QUuid class

I'm using the QUuid class in my project and for testing and debugging purposes it would be very nice to see the QUuid objects in human readable form instead of their low-level form.
For some reason, the people at Qt have not included a dump method for this type so I attempted to create one on my own, following this documentation and this guide.
I'm not familiar with Python so unfortunately, I could not get something running. Could someone help me create such a function that does nothing more than display the output of QUuid::toString() in the value column of Qt Creator?
Edit:
Mitko's solution worked perfectly. I expanded it a bit so the details can still be read if so desired:
from dumper import *
import gdb
def qdump__QUuid(d, value):
this_ = d.makeExpression(value)
finalValue = gdb.parse_and_eval("%s.toString()" % (this_))
d.putStringValue(finalValue)
d.putNumChild(4)
if d.isExpanded():
with Children(d):
d.putSubItem("data1", value["data1"])
d.putSubItem("data2", value["data2"])
d.putSubItem("data3", value["data3"])
d.putSubItem("data4", value["data4"])
The following python script should do the job:
from dumper import *
import gdb
def qdump__QUuid(d, value):
this = d.makeExpression(value)
stringValue = gdb.parse_and_eval("%s.toString()" % this)
d.putStringValue(stringValue)
d.putNumChild(0)
The easiest way to use it with Qt Creator is to just paste these lines at the end of your <Qt-Creator-Install-Dir>/share/qtcreator/debugger/personaltypes.py file. In this case you can skip the first line, as it's already in the file.
As the personaltypes.py file is overwritten when you update Qt Creator you might want to put the script above in its own file. In that case you'll need to configure Qt Creator to use your file. You can do this by going to Tools > Options... > Debugger > GDB > Extra Debugging Helpers > Browse and selecting your file.
Note:
This script will only work inside Qt Creator, since we use its specific dumper (e.g. putStringValue).
We call QUuid::toString() which creates a QString object. I'm not sure exactly how gdb and python handle this, and if there is a need to clean this up in order to avoid leaking memory. It's probably not a big deal for debugging, but something to be aware of.

MS Access application opened from Python script can't quit if Tk() loop is called

I have stucked with a specific problem. I am working on Python script which reads data from MS Access database (.mdb) using VBA API and displays it in GUI tables using tkintertable module.
The problem is that after script terminates the MSACCESS.exe process is keeping alive in the process list.
When I comment mainloop() method for the root window the problem disappears.
Explicit call of access.quit() does not solve the problem. It makes it worse: the script terminates, but the MS Access process makes visible, I see it's window, but can't close it, because it appears more and more.
I removed all the unnecessary lines from the code to localize the problem:
#!C:\Python343\python
from comtypes.client import CreateObject
from tkinter import *
access = CreateObject('Access.Application')
root = Tk()
root.mainloop() # if I comment this line, everything works
# access.quit() - does not help: MS Access window gets visible and immortal
#
Can one give any clue of why this happens?
Thanks in advance for any advice.
Python version: 3.4.3.
MS Office: 2013.
Unfortunately, I can't switch to pypyodbc or other packages, because the script is big and it is not convenient to redesign it. Now it uses VBA API (OpenRecordSet, MoveFirst, MoveLast methods etc.), but pypyodbc does not mirror this API AFAIK.
Now I use a workaround (killing of the MSACCESS.EXE application). I will post it here. Probably, it will be useful for one who stuck with the same problem:
def close_by_force(app): # Took this function from https://stackoverflow.com/
# questions/10221150/cant-close-excel-completely-using-win32com-on-python,
# but had to redesign it to be usable to work with COM objects
import win32process
import win32gui
import win32api
import win32con
# Get the window's process id's
hwnd = app.hWndAccessApp()
t, p = win32process.GetWindowThreadProcessId(hwnd)
# Ask window nicely to close
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
# Allow some time for app to close
time.sleep(10) # not really necessary
# If the application didn't close, force close
try:
#print('pid='+str(p))
handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
if handle:
win32api.TerminateProcess(handle, 0)
win32api.CloseHandle(handle)
except:
pass
...
access = CreateObject('Access.Application')
DBEngine = access.DBEngine
db = DBEngine.OpenDatabase("C:\<my_db_path>")
.... some code (working with the database) ...
close_by_force(access.Application) # this is the crucial line
As I found in web, this problem is an old one and was discussed on different topics, but I don't see the exact solution anywhere, for example:
http://www.xtremevbtalk.com/showthread.php?t=298607
In C#, How should i close running threads ( Access DB )?
http://python-list.python.narkive.com/gCMlrB8M/using-excel-with-python
Found also that I can use something like
System.Runtime.InteropServices.Marshal.ReleaseComObject(access), but I can't found any link where may I get the related Python packages to use these classes.
--
Kind Regards,
Alexander.

Add suggestions to python session autocomplete that appear in IPython notebook too

I'm trying to add bespoke suggestions to the interactive python tab auto complete. I found this toy example on the interweb
import readline, rlcompleter
addrs = ['angela#domain.com', 'michael#domain.com', 'david#test.com']
class mycompleter(rlcompleter.Completer):
def completer(self, text, state):
options = [x for x in addrs if x.startswith(text)]
try:
return options[state]
except IndexError:
return None
readline.set_completer(mycompleter().completer)
readline.parse_and_bind("tab: complete")
This works very nicely in python if I save it in a module and them import it. It also works in IPython if I paste it into an active session using the %paste magic.
However, I can't get it to work in an IPython Notebook, either by loading a module or by running it in a cell. I've found the ipython docs about their extension to the readline module but this hasn't helped. I've tried inheriting from IPCompleter objects, and using rlcompete methods etc, but this doesn't seem to have helped.
Any suggestions about how to add things to the autocomplete suggestions in a way that works in plain python and IPython Notebook
Thanks
Niall
UPDATE:
Ultimately, I'm looking of a way to add functionality to a module so that it can dynamically update the session autocomplete list (ideally for args for a specific set of functions so that it doesn't pollute the suggestions).
There is a way to do it, which is not the recommended one but works.
def my_matches(test):
# might want to be smarter here
return ['angela#domain.com', 'michael#domain.com', 'david#test.com']
ip = get_ipython()
ip.Completer.matchers.append(my_matches)
# it works
The old ways require setting hooks, but I haven't used it and is pretty old
and could be refactored

Categories