Arabic text inverted in Python Tkinter - python-2.7

I'm trying to display Arabic text in a Tkinter program, Windows seems to display them correctly, but gets inverted in Kali Linux for some reason.
test.py file content :
# -*- coding: utf-8 -*-
from Tkinter import *
import Tkinter
import platform
root = Tk()
Label(root, text = "Python version: %s" % platform.python_version()).pack()
Label(root, text = "Tkinter version: %d" % Tkinter.TkVersion).pack()
Label(root, text = "العربية").pack()
root.mainloop()
Result in Windows 10 Pro:
Result in Kali Linux:
Same Python and Tkinter version, but different result, anyone knows the exact reason behind this?

Related

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()

Problems using Colorama on Python 2.7

I'm learning to use colorama in Python, so I installed it and I'm able to import the module with no problems from the Primary Prompt.
>>> import colorama
>>> from colorama import *
>>> print(Fore.BLUE + 'BLUE TEXT')
BLUE TEXT
Now, if I create a small piece of code like this:
#!/usr/bin/env python2.7
from colorama import *
print(Fore.BLUE + 'BLUE TEXT')
I get the following message:
File "colorama_Test.py", line 3, in <module>
from colorama import *
File "/home/olg32/Python/colorama_Test.py", line 5, in <module>
print(Fore.BLUE + 'BLUE TEXT')
NameError: name 'Fore' is not defined
Which tells me that the module is not being found. But as mentioned it was installed and tested successfully from the Primary Prompt. Could it be a path definition issue or something like that? This is the current directory where the module is installed:
usr/local/lib/python2.7/dist-packages/colorama-0.3.7-py2.7.egg
Does this path needs to be defined somewhere? Sorry I'm new on Python.
Any help would be appreciated.
Thank you.
Hopefully you have worked out the answer by now but have you tried specifying Fore?
When I use the colorama module I start with this:
import os, colorama
from colorama import Fore,Style,Back #specifying all 3 types
os.system("mode con: cols=120 lines=30") #sometimes colorama doesnt work
#when double clicking a python app so I use this to "prompt" command line
#and then it works fine colorama.init() should work too
Example code:
import os, colorama
from colorama import Fore,Style,Back
os.system("mode con: cols=120 lines=30")
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
If this doesnt work for you let me know :)

Using gdal_calc multiple times within a Python Script, Issues with Visual C++ for Python 2.7

I've exhausted what I'm capable of currently regarding the script that I have posted below. I am unable to properly call gdal_calc.py with this script. I have received various error message regarding a lack of .dll files to a win32 error.
I have installed and reinstalled GDAL, however I continue to receive an error message that suggests I don't have osgeo, and I cannot install GDAL properly within my Python27 pathway because of an issue with Visual C++ for Python because I either don't have the proper .bat file OR I get this message.
fatal error C1083: Cannot open include file: 'cpl_port.h': No such file or directory
I would appreciate even a direction to be point in, because I am a novice and this is over my head.
Thanks,
import os
import sys
from osgeo import gdal
from gdalconst import *
import numpy as np
import math
import subprocess
from subprocess import call
import math
import PIL
from PIL import Image
# constants
gdalTranslate = r'C:\\Program Files (x86)\\GDAL\\gdal_translate.exe'
src = r"C:\Users\jack\Desktop\RUA_FIL\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA.img"
srcVH = r"C:\Users\jack\Desktop\RUA_FIL\IMG-VH-ALOS2110871010-160611-HBQR1.5RUA.img"
dstVH = r"C:\Users\jack\Desktop\New_Trash\vhFloat32-3.img"
dst = r"C:\\Users\jack\Desktop\\New_Trash\hvFloat32-3.img"
cmd = "-ot Float32 -of HFA" # hopefully this works
#gdalCalc = r'C:\Python27\ArcGIS10.4\Scripts\dist\gdal_calc.exe'
#hvFloat32 = r"C:\Users\jack\Desktop\New_Trash\hvFloat32-1.img"
#vhFloat32 = r"C:\Users\jack\Desktop\New_Trash\hvFloat32-1.img"
#prevName = r"C:\Users\jack\Desktop\RUA_FIL\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA"
#newName = r"C:\Users\jack\Desktop\RUA_FIL\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA.img"
#os.rename(prevName,newName)
# setting def
#def gdal_Translate (item):
#return item
hvfullCmd = ' '.join([gdalTranslate, cmd, gdal_Translate(src), gdal_Translate(dst)])
subprocess.Popen(hvfullCmd)
vhfullCmd = ' '.join([gdalTranslate,cmd,gdal_Translate(srcVH),gdal_Translate(dstVH)])
subprocess.Popen(vhfullCmd)
# Run gdal_calc.py for HV
try:
os.system('C:\Users\jack\Python\QGIS Python Scripts\ridofZs.py')
except:
print ("This isn't working")
sys.exit()
subprocess.call([sys.executable,'C:\Program Files (x86)\GDAL\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\hvFloat32.img', '--outfile=C:\Users\jack\Desktop\New_Trash\NEWCALCHV-2.img','--calc=A*(A>=1)'])
# Run gdal_calc.py for VH
#subprocess.call([sys.executable, 'C:\OSGeo4W64\bin\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\vhFloat32.img', '--outfile=C:\Users\jack\Desktop\New_Trash\NEWCALCVH-2.img','--calc=A*(A>=1)'])
# Run gdal_calc.py to dB for HV
#subprocess.call([sys.executable, 'C:\OSGeo4W64\bin\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\NEWCALCHV-2.img', '--outfile=C:\Users\jack\Desktop\New_Trash\HVindB.img','--calc=10*log10(power(A,2))-83'])
# Run gdal_calc.py to dB for HV
#subprocess.call([sys.executable, 'C:\OSGeo4W64\bin\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\NEWCALCVH-2.img', '--outfile=C:\Users\jack\Desktop\New_Trash\VHindB.img','--calc=10*log10(power(A,2))-83'])
# Open Rasters using GDAL
hvRaster = gdal.Open("C:\\Users\\jack\\Desktop\\New_Trash\\hvFloat32.img")
vhRaster = gdal.Open("C:\\Users\\jack\\Desktop\\New_Trash\\vhFloat32.img")
# Get RasterBand
hvRasterBand = hvRaster.GetRasterBand(1)
vhRasterBand = vhRaster.GetRasterBand(1)
# Get Raster Mean
hvMean = hvRasterBand.GetStatistics(0,1)[2]
vhMean = vhRasterBand.GetStatistics(0,1)[2]
#### Maybe not needed
print hvMean
print vhMean
# calculate stDev
rasterList = (hvMean,vhMean)
stDev = np.std(rasterList)
#print stDev
if stDev >= 0.06:
print "The imagery isn't acceptable"
if stDev <= 0.06:
print "The imagery is acceptable"

How to convert CJK Extention B in QLineEdit of Python3-PyQt4 to utf-8 to Processing it with regex

I have a code like that:
#!/usr/bin/env python3
#-*-coding:utf-8-*-
from PyQt4 import QtGui, QtCore
import re
.....
str = self.lineEdit.text() # lineEdit is a object in QtGui.QLineEdit class
# This line thanks to Fedor Gogolev et al from
#https://stackoverflow.com/questions/12214801/print-a-string-as-hex-bytes
print('\\u'+"\\u".join("{:x}".format(ord(c)) for c in str))
# u+20000-u+2a6d6 is CJK Ext B
cjk = re.compile("^[一-鿌㐀-䶵\U00020000-\U0002A6D6]+$",re.UNICODE)
if cjk.match(str):
print("OK")
else:
print("error")
when I inputted "敏感詞" (0x654F,0x611F, 0x8A5E in utf16 respectively), the result was:
\u654f\u611f\u8a5e
OK
but when I input "詞𠀷𠂁𠁍" (0x8A5E, 0xD840 0xDC37, 0xD840 0xDC81, 0xD840 0xDC4D in utf-16) in which there were 3 characters from CJK Extention B Area. The result which is not expected is:
\u8a5e\ud840\udc37\ud840\udc81\ud840\udc4d
error
how can I processed these CJK characters with converting to utf-8 to be processed suitabliy with re of Python3?
P.S.
the value from sys.maxunicode is 1114111, it might be UCS-4. Hence, I think that the question seems not to be the same as
python regex fails to match a specific Unicode > 2 hex values
another code:
#!/usr/bin/env python3
#-*-coding:utf-8-*-
import re
CJKBlock = re.compile("^[一-鿌㐀-䶵\U00020000-\U0002A6D6]+$") #CJK ext B
print(CJKBlock.search('詞𠀷𠂁𠁍'))
returns <_sre.SRE_Match object; span=(0, 4), match='詞𠀷𠂁𠁍'> #expected result.
even I added self.lineEdit.setText("詞𠀷𠂁𠁍") inside __init__ function of the window class and executed it, the word in LineEdit shows appropriately, but when I pressed enter, the result was still "error"
version:
Python3.4.3
Qt version: 4.8.6
PyQt version: 4.10.4.
There were a few PyQt4 bugs following the implemetation of PEP-393 that can affect conversions between QString and python strings. If you use sip to switch to the v1 API, you should probably be able to confirm that the QString returned by the line-edit does not contain surrogate pairs. But if you then convert it to a python string, the surrogates should appear.
Here is how to test this in an interactive session:
>>> import sip
>>> sip.setapi('QString', 1)
>>> from PyQt4 import QtGui
>>> app = QtGui.QApplication([])
>>> w = QtGui.QLineEdit()
>>> w.setText('詞𠀷𠂁𠁍')
>>> qstr = w.text()
>>> qstr
PyQt4.QtCore.QString('詞𠀷𠂁𠁍')
>>> pystr = str(qstr)
>>> print('\\u' + '\\u'.join('{:x}'.format(ord(c)) for c in pystr))
\u8a5e\u20037\u20081\u2004d
Of course, this last line does not show surrogates for me, because I cannot do the test with PyQt-4.10.4. I have tested with PyQt-4.11.1 and PyQt-4.11.4, though, and I did not get see any problems. So you should try to upgrade to one of those.

How to open a python program within python

I'm working on a program using tkinter (2.7) that when a button is clicked, it opens a separate python program. What I have been trying to do is give the button a command and define it as the separate program. This is what I have so far:
from Tkinter import *
from ttk import *
import os
app = Tk()
app.title("iClassics")
app.geometry("450x300+200+200")
#Definitions
def mTetris():
subprocess.Popen("Tetris.py")
#Heading
headlabel = Label(text="iClassics", font=("Times", 30), background=("blue")).pack()
#Buttons
buttontetris = Button(app, text="Tetris", command=mTetris).pack()
buttonpong = Button(app, text="Pong").pack()
buttonbrick = Button(app, text="Brick Breaker").pack()
buttonsnake = Button(app, text = "Snake").pack()
app.mainloop()
Why can't I open my tetris.py on click?
Take a look at popen.
You shoold call it this way:
subprocess.Popen(["python", "tetris.py"])