How to prevent VSCode from reordering python imports across statements? - python

This is the correct way to import Gtk3 into python:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject
When I save such code in VSCode with "editor.formatOnSave": true, it gets reordered to:
from gi.repository import Gtk, Gdk
import gi
gi.require_version('Gtk', '3.0')
which makes Gtk to be loaded before I have the chance to specify the version I am using, which at very least leads to the following warning being displayed:
PyGIWarning: Gtk was imported without specifying a version first. Use gi.require_version('Gtk', '4.0') before import to ensure that the right version gets loaded.
or worse, get me an exception like:
ValueError: Namespace Gtk is already loaded with version 4.0
Now, I like VSCode code formatting, but I don't want it to reorder my imports, specially not across statements (being that imports in python have side effects). How to properly use VSCode's Python code formatter with Gtk?

To prevent VSCode from reordering Python imports across statements, you can configure the editor to use a specific Python code formatter that maintains the order of the imports as they are in the original code. Here's how you can do it:
Install the Python extension for VSCode if you haven't already done so.
Install a Python code formatter that maintains the order of imports, such as isort or yapf. You can do this by running the command pip install isort or pip install yapf in your terminal.
In VSCode, open the settings by clicking on the gear icon in the bottom left corner and selecting "Settings".
Search for "Python › Formatting: Provider" in the search bar.
Select "Edit in settings.json" to edit the settings.json file.
Add the following line to the file, depending on which code formatter you installed:
For isort: "python.formatting.provider": "isort"
For yapf: "python.formatting.provider": "yapf"
Save the file and close the settings.

Related

Error: no module named gtk.glade

I researched and tried this for two days now and I cannot get gtk to work on Windows 7 with Python 3.4! Whenever I launch my .py file on Python 3.4 with import gtk, I get No module named gtk! I installed pygobject but it did not help. Even gtk3-demo command works in the windows cmd prompt.
I finally got gtk to import (I think) by copying the GTK directory right to C:\Python34\Lib. But now I have a problem with gtk.glade.
Where is this? Where do I copy it from and to where?
You are possibly using an outdated tutorial, see the current Python GTK 3 tutorial for a more up-to-date reference.
In particular, the way to import GTK has changed in GTK3 to:
from gi.repository import Gtk
And instead of libglade, you would use the newer Gtk.Builder class like so:
ui = Gtk.Builder()
ui.add_from_file("my_glade_file.glade")
(you still develop the UI using Glade, it is only how you access it from your program that has changed).

No module named when using PyInstaller

I try to compile a Python project under Windows 7 using PyInstaller. The project works fine, there are no issues, however when I try to compile it the result doesn't work. Though I get no warnings during compilation there are many in the warnmain.txt file in the build directory: warnmain.txt
I don't really understand those warnings, for example "no module named numpy.pi" since numpy.pi is no module but a number. I never tried to import numpy.pi. I did import numpy and matplotlib explicitly. In addition I'm using PyQt4. I thought the error might be related to those libraries.
However I was able to compile a simple script which uses numpy succesfully:
import sys
from PyQt4 import QtGui, QtCore
import numpy as np
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.pb = QtGui.QPushButton(str(np.pi), self)
app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
Successfully here means that the created executable file actually showed the desired output. However there is also a warnmain.txt file created which contains exactly the same 'warnings' as the one before. So I guess the fact that compiling my actual project does not give any success is not (or at least not only) related to those warnings. But what else could be the error then? The only output during compilation are 'INFO's and none of the is a negative statement.
I did not specify an additional hook directory but the hooks where down using the default directory as far as I could read from the compile output, e.g. hook-matplotlib was executed. I could not see any hook for numpy neither could I for my small example script but this one worked. I used the following imports in my files (not all in the same but in different ones):
import numpy as np
import matplotlib.pyplot as ppl
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from PyQt4 import QtGui, QtCore
import json
import sys
import numpy # added this one later
import matplotlib # added this one later
Since PyInstaller does not give any errors/warnings I could not figure out if the problem is related to the libraries or if there is something else to be considered.
Had a similar problem with no module named FileDialog. Discovered that with version 3.2, I could use
pyinstaller --hidden-import FileDialog ...
instead of modifying my main script.
See Listing Hidden Imports documentation
Pyinstaller won't see second level imports. So if you import module A, pyinstaller sees this. But any additional module that is imported in A will not be seen.
There is no need to change anything in your python scripts. You can directly add the missing imports to the spec file.
Just change the following line:
hiddenimports=[],
to
hiddenimports=["Tkinter", "FileDialog"],
If you are getting ModuleNotFoundError: No module named ... errors and you:
call PyInstaller from a directory other than your main script's directory
use relative imports in your script
then your executable can have trouble finding the relative imports.
This can be fixed by:
calling PyInstaller from the same directory as your main script
OR removing any __init__.py files (empty __init__.py files are not required in Python 3.3+)
OR using PyInstaller's paths flag to specify a path to search for imports. E.g. if you are calling PyInstaller from a parent folder to your main script, and your script lives in subfolder, then call PyInstaller as such:
pyinstaller --paths=subfolder subfolder/script.py.
The problem were some runtime dependencies of matplotlib. So the compiling was fine while running the program threw some errors. Because the terminal closed itself immediately I didn't realize that. After redirecting stdout and stderr to a file I could see that I missed the libraries Tkinter and FileDialog. Adding two imports at the top of the main solved this problem.
I was facing the same problem and the following solution worked for me:
I first removed the virtual environment in which I was working.
Reinstalled all the modules using pip (note: this time I did not create any virtual environment).
Then I called the pyinstaller.
The .exe file created thereafter executed smoothly, without any module import error.
I had the same problem with pyinstaller 3.0 and weblib. Importing it in the main didn't help.
Upgrading to 3.1 and deleting all build files helped.
pip install --upgrade pyinstaller
If the matter is that you don't need Tkinter and friends because you are using PyQt4, then it might be best to avoid loading Tkinter etc altogether. Look into /etc/matplotlibrc and change the defaults to PyQt4, see the 'modified' lines below:
#### CONFIGURATION BEGINS HERE
# The default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
# CocoaAgg MacOSX Qt4Agg Qt5Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG
# Template.
# You can also deploy your own backend outside of matplotlib by
# referring to the module name (which must be in the PYTHONPATH) as
# 'module://my_backend'.
#modified
#backend : TkAgg
backend : Qt4Agg
# If you are using the Qt4Agg backend, you can choose here
# to use the PyQt4 bindings or the newer PySide bindings to
# the underlying Qt4 toolkit.
#modified
#backend.qt4 : PyQt4 # PyQt4 | PySide
backend.qt4 : PyQt4 # PyQt4 | PySide
May not be a good practice but installing pyinstaller in the original environment used in my project (instead of a separate venv) helped resolve ModuleNotFoundError
I had similar problem with PySimpleGUI.
The problem was, pyinstaller was installed in different directory.
SOLUTION (solved for me) : just install pyinstaller in the same directory in which the file is present (that to be converted to exe)
If these solutions don't work, simply deleting and reinstalling pyinstaller can fix this for you (as it did for me just now).
Putting this here for anyone else who might come across this post.
I had the same error. Mine said "ModuleNotFoundError: No module named 'numpy'". I fixed it by typing the following in the cmd:
pip install pyinstaller numpy

Is there a way to get code-hints for gtk3 and python working on aptana?

My situation is Aptana eclipse plug-in installed and working properly.
If I from gi.repository import Gtk the code completion I'm used to from import gtk is gone. Any solutions or is it just a bug?
My interim solution is keeping an import gtk\ngtk. in a clipboard manager and dropping it in when I need hints.
Yes, there is!
You should add gi to the forced builtins and you'll get a code completion:
Go to the Window->Preferences, PyDev->Interpreter python section and add gi to the "Forced builtin" tab for each interpreter you would like to use Gtk3.
More about this:
http://pydev.org/manual_101_interpreter.html
from gi.repository import Gtk
is not same like
import gtk
With the statement "
from gi.repository import Gtk
your are importing Gtk 3. With
import gtk
your are importing Gtk 2.
I would say that you code completion doesn't know Gtk 3.
maybe useful:
Tutorial for Gtk 3 http://readthedocs.org/docs/python-gtk-3-tutorial/en/latest/index.html
http://live.gnome.org/PyGObject

Understanding gi.repository

I have troubles understanding gi.repository
I use this contruction in my code
from gi.repository import Gtk
But if I want to use some component I get import error
I searched and I got it worked for some components, like GtkSource, Vte, GLib, ...
So my code is like
from gi.repository import Gtk, GtkSource, Vte, GLib
Everything worked fine, but if I want to add matplotlib to draw on my canvas I get and error
enter code/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py:40: Warning: specified class size for type `PyGtkGenericCellRenderer' is smaller than the parent type's `GtkCellRenderer' class size
from gtk import _gtk
/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata: assertion `node != NULL' failed
from gtk import _gtk
/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_ascii_strncasecmp: assertion `s2 != NULL' failed
from gtk import _gtk
Segmentation fault (core dumped) here
How can I get matplotlib working with gi.repository?
Thank you
It seems that the support for Gtk3 it's been added recently. I guess it will take some time till it's available in the main distributions.
The best solution would be to download and install the latest version.
As a workaround to avoid installing stuff in my Ubuntu 11.10 I have dowloaded backend_gtk3.py and backend_gtk3agg.py files and imported directly like:
from gi.repository import Gtk
from matplotlib.figure import Figure
from backend_gtk3agg import FigureCanvasGTK3Agg as FigCanvas
I had to change backend_gtk3agg.py line 6 where it says:
import backend_agg
with
from matplotlib.backends import backend_agg
, so it can import the module from my installation.
So far it works for me, but I understand this solution can't work with different versions of matplotlib.
That's a very good question. I'm afraid the answer might be "you can't." Matplotlib's GTK backend is written for PyGTK, the old-style Python bindings for GTK. The gi.repository package is the new-style Python bindings. I don't know one way or the other whether they can mix or not, but your results seem to indicate they can't.

Discover what window is active on Gnome/Linux/Ubuntu from Python?

Is there any way to get a list of all windows that are open at present and see what window is at the top (i.e. active?) from Python?
This is using Gnome on Ubuntu Linux.
wnck looks like it might do this, but it's very lacking in documentation.
Here's the same code using the modern GObject Introspection libraries instead of the now deprecated PyGTK method Josh Lee posted:
from gi.repository import Gtk, Wnck
Gtk.init([]) # necessary if not using a Gtk.main() loop
screen = Wnck.Screen.get_default()
screen.force_update() # recommended per Wnck documentation
window_list = screen.get_windows()
active_window = screen.get_active_window()
As for documentation, check out the Libwnck Reference Manual. It is not specific for python, but the whole point of using GObject Introspection is to have the same API across all languages, thanks to the gir bindings.
Also, Ubuntu ships with both wnck and its corresponding gir binding out of the box, but if you need to install them:
sudo apt-get install libwnck-3-* gir1.2-wnck-3.0
This will also install libwnck-3-dev, which is not necessary but will install useful documentation you can read using DevHelp
import wnck
screen = wnck.screen_get_default()
window_list = screen.get_windows()
active_window = screen.get_active_window()
See also Get active window title in X, and WnckScreen in the documentation. Other questions containing wnck have useful code samples.

Categories