Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Enable console with Python3 / PyQt5
  • Loading branch information
m-kuhn committed Mar 29, 2016
1 parent a4ed8e0 commit e133b42
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 71 deletions.
4 changes: 2 additions & 2 deletions python/console/console_compile_apis.py
Expand Up @@ -60,7 +60,7 @@ def _preparationFinished(self):
if os.path.exists(self._pap_file):
os.remove(self._pap_file)
self.ui.label.setText(QCoreApplication.translate("PythonConsole", "Saving prepared file..."))
prepd = self._api.savePrepared(unicode(self._pap_file))
prepd = self._api.savePrepared(self._pap_file)
rslt = self.trUtf8("Error")
if prepd:
rslt = QCoreApplication.translate("PythonConsole", "Saved")
Expand All @@ -78,7 +78,7 @@ def prepareAPI(self):
self._api = QsciAPIs(self.qlexer)
self._api.apiPreparationFinished.connect(self._preparationFinished)
for api_file in self._api_files:
self._api.load(unicode(api_file))
self._api.load(api_file)
try:
self._api.prepare()
except Exception as err:
Expand Down
76 changes: 38 additions & 38 deletions python/console/console_editor.py
Expand Up @@ -18,7 +18,6 @@
***************************************************************************/
Some portions of code were taken from https://code.google.com/p/pydee/
"""

from PyQt.QtCore import Qt, QObject, QEvent, QSettings, QCoreApplication, QFileInfo, QSize
from PyQt.QtGui import QFont, QFontMetrics, QColor, QKeySequence, QCursor
from PyQt.QtWidgets import QShortcut, QMenu, QApplication, QWidget, QGridLayout, QSpacerItem, QSizePolicy, QFileDialog, QTabWidget, QTreeWidgetItem, QFrame, QLabel, QToolButton, QMessageBox
Expand Down Expand Up @@ -48,7 +47,7 @@ def __init__(self, window, tab, *args):
self.window = window
self.tab = tab
self._handlers = {}
for shortcut, handler in KeyFilter.SHORTCUTS.iteritems():
for shortcut, handler in KeyFilter.SHORTCUTS.items():
modifiers = shortcut[0]
if not isinstance(modifiers, list):
modifiers = [modifiers]
Expand Down Expand Up @@ -266,7 +265,7 @@ def setLexers(self):
else:
apiPath = self.settings.value("pythonConsole/userAPI", [])
for i in range(0, len(apiPath)):
self.api.load(unicode(apiPath[i]))
self.api.load(apiPath[i])
self.api.prepare()
self.lexer.setAPIs(self.api)

Expand Down Expand Up @@ -418,19 +417,20 @@ def objectListEditor(self):
self.parent.pc.objectListButton.setChecked(True)

def codepad(self):
import urllib2
import urllib
import urllib.request
import urllib.parse
import urllib.error
listText = self.selectedText().split('\n')
getCmd = []
for strLine in listText:
getCmd.append(unicode(strLine))
getCmd.append(strLine)
pasteText = u"\n".join(getCmd)
url = 'http://codepad.org'
values = {'lang': 'Python',
'code': pasteText,
'submit': 'Submit'}
try:
response = urllib2.urlopen(url, urllib.urlencode(values))
response = urllib.request.urlopen(url, urllib.parse.urlencode(values))
url = response.read()
for href in url.split("</a>"):
if "Link:" in href:
Expand All @@ -443,9 +443,9 @@ def codepad(self):
QApplication.clipboard().setText(link)
msgText = QCoreApplication.translate('PythonConsole', 'URL copied to clipboard.')
self.parent.pc.callWidgetMessageBarEditor(msgText, 0, True)
except urllib2.URLError as e:
except urllib.error.URLError as e:
msgText = QCoreApplication.translate('PythonConsole', 'Connection error: ')
self.parent.pc.callWidgetMessageBarEditor(msgText + str(e.args), 0, True)
self.parent.pc.callWidgetMessageBarEditor(msgText + repr(e.args), 0, True)

def hideEditor(self):
self.parent.pc.splitterObj.hide()
Expand Down Expand Up @@ -506,10 +506,10 @@ def _runSubProcess(self, filename, tmp=False):
try:
## set creationflags for running command without shell window
if sys.platform.startswith('win'):
p = subprocess.Popen(['python', unicode(filename)], shell=False, stdin=subprocess.PIPE,
p = subprocess.Popen(['python', filename], shell=False, stdin=subprocess.PIPE,
stderr=subprocess.PIPE, stdout=subprocess.PIPE, creationflags=0x08000000)
else:
p = subprocess.Popen(['python', unicode(filename)], shell=False, stdin=subprocess.PIPE,
p = subprocess.Popen(['python', filename], shell=False, stdin=subprocess.PIPE,
stderr=subprocess.PIPE, stdout=subprocess.PIPE)
out, _traceback = p.communicate()

Expand All @@ -529,15 +529,15 @@ def _runSubProcess(self, filename, tmp=False):
file = file + tmpFileTr
if _traceback:
msgTraceTr = QCoreApplication.translate('PythonConsole', '## Script error: {0}').format(file)
print "## %s" % datetime.datetime.now()
print unicode(msgTraceTr)
print("## {}".format(datetime.datetime.now()))
print(msgTraceTr)
sys.stderr.write(_traceback)
p.stderr.close()
else:
msgSuccessTr = QCoreApplication.translate('PythonConsole',
'## Script executed successfully: {0}').format(file)
print "## %s" % datetime.datetime.now()
print unicode(msgSuccessTr)
print("## {}".format(datetime.datetime.now()))
print(msgSuccessTr)
sys.stdout.write(out)
p.stdout.close()
del p
Expand All @@ -547,10 +547,10 @@ def _runSubProcess(self, filename, tmp=False):
IOErrorTr = QCoreApplication.translate('PythonConsole',
'Cannot execute file {0}. Error: {1}\n').format(filename,
error.strerror)
print '## Error: ' + IOErrorTr
print('## Error: ' + IOErrorTr)
except:
s = traceback.format_exc()
print '## Error: '
print('## Error: ')
sys.stderr.write(s)

def runScriptCode(self):
Expand Down Expand Up @@ -602,7 +602,7 @@ def syntaxCheck(self, filename=None, fromContextMenu=True):
eline = None
ecolumn = 0
edescr = ''
source = unicode(self.text())
source = self.text()
try:
if not filename:
filename = self.parent.tw.currentWidget().path
Expand All @@ -611,7 +611,7 @@ def syntaxCheck(self, filename=None, fromContextMenu=True):
source = source.encode('utf-8')
if isinstance(filename, type(u"")):
filename = filename.encode('utf-8')
compile(source, str(filename), 'exec')
compile(source, filename, 'exec')
except SyntaxError as detail:
eline = detail.lineno and detail.lineno or 1
ecolumn = detail.offset and detail.offset or 1
Expand Down Expand Up @@ -644,7 +644,7 @@ def syntaxCheck(self, filename=None, fromContextMenu=True):
return True

def keyPressEvent(self, e):
t = unicode(e.text())
t = e.text()
startLine, _, endLine, endPos = self.getSelection()
line, pos = self.getCursorPosition()
self.autoCloseBracket = self.settings.value("pythonConsole/autoCloseBracketEditor", False, type=bool)
Expand Down Expand Up @@ -761,7 +761,7 @@ def __init__(self, parent, parentConsole, filename, readOnly):

def loadFile(self, filename, modified):
self.newEditor.lastModified = QFileInfo(filename).lastModified()
fn = codecs.open(unicode(filename), "rb", encoding='utf-8')
fn = codecs.open(filename, "rb", encoding='utf-8')
txt = fn.read()
fn.close()
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
Expand All @@ -779,10 +779,10 @@ def save(self, fileName=None):
if self.path is None:
saveTr = QCoreApplication.translate('PythonConsole',
'Python Console: Save file')
self.path = str(QFileDialog().getSaveFileName(self,
saveTr,
self.tw.tabText(index) + '.py',
"Script file (*.py)"))
self.path = QFileDialog().getSaveFileName(self,
saveTr,
self.tw.tabText(index) + '.py',
"Script file (*.py)")
# If the user didn't select a file, abort the save operation
if len(self.path) == 0:
self.path = None
Expand All @@ -792,7 +792,7 @@ def save(self, fileName=None):
'Script was correctly saved.')
self.pc.callWidgetMessageBarEditor(msgText, 0, True)
# Rename the original file, if it exists
path = unicode(self.path)
path = self.path
overwrite = QFileInfo(path).exists()
if overwrite:
try:
Expand Down Expand Up @@ -979,7 +979,7 @@ def contextMenuEvent(self, e):
def closeOthers(self):
idx = self.idx
countTab = self.count()
for i in range(countTab - 1, idx, -1) + range(idx - 1, -1, -1):
for i in list(range(countTab - 1, idx, -1)) + list(range(idx - 1, -1, -1)):
self._removeTab(i)

def closeAll(self):
Expand Down Expand Up @@ -1009,14 +1009,14 @@ def newTabEditor(self, tabName=None, filename=None):
if filename:
readOnly = not QFileInfo(filename).isWritable()
try:
fn = codecs.open(unicode(filename), "rb", encoding='utf-8')
fn = codecs.open(filename, "rb", encoding='utf-8')
fn.read()
fn.close()
except IOError as error:
IOErrorTr = QCoreApplication.translate('PythonConsole',
'The file {0} could not be opened. Error: {1}\n').format(filename,
error.strerror)
print '## Error: '
print('## Error: ')
sys.stderr.write(IOErrorTr)
return

Expand All @@ -1028,7 +1028,7 @@ def newTabEditor(self, tabName=None, filename=None):
self.addTab(self.tab, self.iconTab, tabName + ' (ro)' if readOnly else tabName)
self.setCurrentWidget(self.tab)
if filename:
self.setTabToolTip(self.currentIndex(), unicode(filename))
self.setTabToolTip(self.currentIndex(), filename)
else:
self.setTabToolTip(self.currentIndex(), tabName)

Expand Down Expand Up @@ -1108,14 +1108,14 @@ def restoreTabsOrAddNew(self):

def restoreTabs(self):
for script in self.restoreTabList:
pathFile = unicode(script)
pathFile = script
if QFileInfo(pathFile).exists():
tabName = pathFile.split('/')[-1]
self.newTabEditor(tabName, pathFile)
else:
errOnRestore = QCoreApplication.translate("PythonConsole",
"Unable to restore the file: \n{0}\n").format(pathFile)
print '## Error: '
print('## Error: ')
s = errOnRestore
sys.stderr.write(s)
self.parent.updateTabListScript(pathFile, action='remove')
Expand Down Expand Up @@ -1150,7 +1150,7 @@ def listObject(self, tab):
tabWidget = self.widget(tab)
if tabWidget:
if tabWidget.path:
pathFile, file = os.path.split(unicode(tabWidget.path))
pathFile, file = os.path.split(tabWidget.path)
module, ext = os.path.splitext(file)
found = False
if pathFile not in sys.path:
Expand All @@ -1161,8 +1161,8 @@ def listObject(self, tab):
dictObject = {}
readModule = pyclbr.readmodule(module)
readModuleFunction = pyclbr.readmodule_ex(module)
for name, class_data in sorted(readModule.items(), key=lambda x: x[1].lineno):
if os.path.normpath(str(class_data.file)) == os.path.normpath(str(tabWidget.path)):
for name, class_data in sorted(list(readModule.items()), key=lambda x: x[1].lineno):
if os.path.normpath(class_data.file) == os.path.normpath(tabWidget.path):
superClassName = []
for superClass in class_data.super:
if superClass == 'object':
Expand All @@ -1185,7 +1185,7 @@ def listObject(self, tab):
iconClass = QgsApplication.getThemeIcon("console/iconClassTreeWidgetConsole.png")
classItem.setIcon(0, iconClass)
dictObject[name] = class_data.lineno
for meth, lineno in sorted(class_data.methods.items(), key=itemgetter(1)):
for meth, lineno in sorted(list(class_data.methods.items()), key=itemgetter(1)):
methodItem = QTreeWidgetItem()
methodItem.setText(0, meth + ' ')
methodItem.setText(1, str(lineno))
Expand All @@ -1197,9 +1197,9 @@ def listObject(self, tab):
classItem.addChild(methodItem)
dictObject[meth] = lineno
self.parent.listClassMethod.addTopLevelItem(classItem)
for func_name, data in sorted(readModuleFunction.items(), key=lambda x: x[1].lineno):
for func_name, data in sorted(list(readModuleFunction.items()), key=lambda x: x[1].lineno):
if isinstance(data, pyclbr.Function) and \
os.path.normpath(str(data.file)) == os.path.normpath(str(tabWidget.path)):
os.path.normpath(data.file) == os.path.normpath(tabWidget.path):
funcItem = QTreeWidgetItem()
funcItem.setText(0, func_name + ' ')
funcItem.setText(1, str(data.lineno))
Expand Down
4 changes: 2 additions & 2 deletions python/console/console_output.py
Expand Up @@ -28,7 +28,7 @@
import sys


class writeOut:
class writeOut(object):

def __init__(self, shellOut, out=None, style=None):
"""
Expand Down Expand Up @@ -265,7 +265,7 @@ def showEditor(self):
def copy(self):
"""Copy text to clipboard... or keyboard interrupt"""
if self.hasSelectedText():
text = unicode(self.selectedText())
text = self.selectedText()
text = text.replace('>>> ', '').replace('... ', '').strip() # removing prompts
QApplication.clipboard().setText(text)
else:
Expand Down

0 comments on commit e133b42

Please sign in to comment.