# -*- coding: cp1252 -*-
### cp1252
### utf-8
# PeJBshell
# Michel Claveau Informatique
# http://mclaveau.com
#
GlobalPVersion="2.08"
from sys import *
from os import *
from os.path import *
from shutil import *
from sets import *
from win32com.client import Dispatch
import sys,time,cStringIO
import os,os.path,shutil
import types
import subprocess
global flagponx
flagponx=False
def chargeponx():
global flagponx,px,pxd
try:
px=Dispatch('ponx.Mci')
pxd=Dispatch('ponxd.Mci')
except:
px=pxd=None
import ponx
import pxie
flagponx=True
def connectpbridge():
clsid='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'
hie=Dispatch(clsid)
for i in range(hie.Count):
instance=hie[i]
try:
if instance.Document.parentWindow.name=='PBridge':
wpx=instance.Document.parentWindow
px=wpx.ponx
pd=wpx.ponxd
htawin=wpx.htawin
print "PBridge (Ponx) connected, OK"
return px,pd,htawin,wpx
except:
pass
return None,None,None,None
def chargepbridge():
global flagponx,px,pxd
try:
px,pxd,htawin,wpx=connectpbridge()
except:
px=pxd=None
#print px.PVersion()
#print pxd.sinverse('ABC')
#import ponx
#import pxie
flagponx=True
#------------------------------Console-début------------------------
def saichr():
while 1:
time.sleep(0.1)
kbd,kbs=gconsole.attendkb()
#print '*'+kbd+'*'+kbs+'*'
if kbd==u'13' and kbs=='Ctrl':
kbs='Ctrl+Return'
vret=gconsole.saisie.value
break
if kbd==u'13' :
kbs='Return'
vret=gconsole.saisie.value
gconsole.saisie.value=''
break
if kbd==u'9' :
kbs='Tab'
vret=gconsole.saisie.value
break
if kbd==u'27': vret='Escape'; break
if kbd==u'38': vret='Up'; break
if kbd==u'40': vret='Down'; break
if kbd==u'112': vret='F1'; break
return vret,kbs
def sai(valeur=''):
global gconsole
txt=str(valeur)
pos=len(txt)
code=None
lig=numlig
flagtab=-1
while 1:
gconsole.saisie.value=txt
k,kbs=saichr()
if kbs=='Tab':
txt=tabcomplet(k, flagtab)
flagtab+=1
continue
#else:
# flagtab=-1
if k=='Escape':
code=k
txt=""
continue
if k=='F1':
startfile('http://ponx.org/ponx/pejbshell.htm')
continue
elif kbs=='Return':
while k.endswith('\n'): k=k[:-1]
while k.endswith('\r'): k=k[:-1]
while k.endswith('\n'): k=k[:-1]
while k.endswith('\r'): k=k[:-1]
while k.endswith('\n'): k=k[:-1]
txt=k
break
elif k=='Up':
lig-=1
if lig<0:
lig=numlig-1
txt=lin[lig]
pos=len(txt)
continue
elif k=='Down':
lig+=1
if lig>=numlig:
lig=0
txt=lin[lig]
pos=len(txt)
continue
return txt,code
def echo(ltxt):
echolist(ltxt)
def echoline(txt):
global gconsole
st=upe(txt)
pas=30000
for i in range(0,len(st),pas):
gconsole.echoline(upe(st[i:i+pas]))
def echonoline(txt):
gconsole.echonoline(txt)
def echoprompt(txt):
#echoline(txt)
echoline(upe(txt))
def echolf(nb=1):
global gconsole
for i in range(nb):
echoline('\r\n')
def echohr(nb=1):
global gconsole
for i in range(nb):
gconsole.writebrut('
')
def echolist(ltxt):
global gconsole
if ltxt:
#if type(ltxt) in (types.StringType,types.StringTypes):
if type(ltxt) in (types.ListType,types.ListType):
for i in ltxt:
echoline(i)
else:
echoline(ltxt)
#------------------------------Console-fin--------------------------
def tabcomplet(txt, flagtab):
if flagtab==-1:
nom=''
pat=''
ltmp=txt.split(' ')
gconsole.tabprefixe=' '.join(ltmp[:-1])
if len(gconsole.tabprefixe)>1:
gconsole.tabprefixe+=' '
nom=ltmp[-1]
if nom.find('\\')>-1:
ltmp=nom.split('\\')
pat='\\'.join(ltmp[:-1])+'\\'
gconsole.tabprefixe+=pat
nom=ltmp[-1]
import subprocess
p=subprocess.Popen('dir '+pat+nom+'* /b', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, bufsize=1)
(data,err)=p.communicate()
tmp=data.replace('\r\n', '\n')
gconsole.tablistpersist=tmp.split('\n')[:-1]
flagtab+=1
try:
vret=gconsole.tabprefixe+gconsole.tablistpersist[flagtab % len(gconsole.tablistpersist)]
except:
vret=''
return vret
def runmacro(fichier):
global pmacro,imacro
data=file(fichier,'r').read()
tmp=data.replace('\r\n', '\n')
pmacro=tmp.split('\n')
imacro=0
def runpymacro(fichier):
global pmacro,imacro
data=file(fichier,'r').read()
pmacro=['MacroPython',data.replace('\r\n', '\n')]
imacro=0
def u1252(chu):
try:
if type(chu) is unicode:
return chu.encode('cp1252','replace')
else:
return chu
except:
return repr(chu)
def u850(chu):
try:
if type(chu) is unicode:
return chu.encode('cp850','replace')
else:
return chu.decode('cp1252').encode('cp850','replace')
except:
return repr(chu)
def u437(chu):
try:
if type(chu) is unicode:
return chu.encode('cp437','replace')
else:
return chu.decode('cp1252').encode('cp437','replace')
except:
return repr(chu)
def upe(chu):
try:
vret=u1252(chu)
except:
vret=repr(chu)
return vret
def uniw32dia(suni, titre=u'Texte unicode', typ=0):
#visu un txt unicode dans une boîte d'alerte
import ctypes
MessageBoxW = ctypes.windll.user32.MessageBoxW
MessageBoxW.argtypes = ctypes.c_int, ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_int
return MessageBoxW(0, suni, titre, typ) #en retour : 6 = OUI 7 = NON
def uniw32diaA(suni, titre=u'Texte unicode', typ=0):
#visu un txt unicode dans une boîte d'alerte
import ctypes
MessageBoxA = ctypes.windll.user32.MessageBoxA
MessageBoxA.argtypes = ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int
return MessageBoxA(0, suni, titre, typ) #en retour : 6 = OUI 7 = NON
def msginfo(titre='Titre',txt='Texte'):
try:
uniw32dia(u1252(txt.decode('utf-8')),u1252(titre.decode('utf-8')))
except:
uniw32dia(u1252(txt),u1252(titre))
def msginfoA(titre='Titre',txt='Texte'):
uniw32diaA(txt,titre)
def lload(fichier):
data=file(fichier,'r').read()
tmp=data.replace('\r\n', '\n')
l=tmp.split('\n')
return l
def lwrite(fichier,lst):
f=file(fichier,"w")
f.write(upe('\r\n'.join(lst)))
f.close()
def bufferin(num):
global lin
if num<0:
return lin[numlig+num]
else:
return lin[num]
def bufferout(num):
global lout
if num<0:
return lout[numlig+num]
else:
return lout[num]
def lbufferin(num):
global lin
if num<0:
return lin[numlig+num].split('\n')
else:
return lin[num].split('\n')
def lbufferout(num):
global lout
if num<0:
return lout[numlig+num].split('\n')
else:
return lout[num].split('\n')
def cmdp2(lst=None):
a = os.popen4(upe(lst[0]))
for i in lst[1:]:
if i!='':
a[0].write(i+'\r\n')
a[0].flush()
#lsterr=a[0].readlines()
lret=a[1].readlines()
if len(lret)>1:
lret='\n'.join(lret)
else:
lret=lret
return lret
def cmdp(lst=None):
#p=subprocess.Popen(u850(''.join(lst)), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
p=subprocess.Popen('cmd /u/c'+u850(''.join(lst)), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
tdata=p.stdout.read()
#print "tdata",
#print tdata.decode('cp850').encode('cp1252','replace')
if ord(tdata[1])==0:
data=tdata.decode('utf-16')
#print 'utf-16',len(data)
else:
data=tdata.decode('cp850')
#print 'cp850',len(data),ord(tdata[0]),ord(tdata[1])
#tmp=data.decode('cp850').encode('cp1252','replace')
#pxd.msginfo(str(type(data)),unicode(data,'cp850'))
#print "data",data
"""
c=''
for i in data:
j=ord(i)
if j>255:
c+=''+str(j)+';'
else:
c+=i
"""
def c255(c):
if ord(c)>255:
return ''+str(ord(c))+';'
else:
return c
c=''.join([c255(i) for i in data])
tmp=c.encode('cp1252','replace')
tmp=tmp.replace('\r\n', '\n')
lret=tmp.split('\n')
#echolist(lret)
err=p.stderr.read()
if len(err)>0:
tmperr=err.replace('\r\n', '\n')
lsterr=tmperr.split('\n')
echo("Erreur cmd. ")
echolist(err)
if len(lret)>1:
lret='\n'.join(lret)
else:
lret=lret
#echo(lst)
return lret
def fichierw(txt, encod='cp1252'):
f=file("temp.txt","wu")
f.write(txt.decode('cp850').encode(encod,'replace'))
f.close()
def fichierwu(txt, encod='utf-8'):
f=file("temp.txt","wb")
try:
f.write(txt.decode('cp1252'))
except:
f.write(txt.decode('cp1252').encode(encod,'replace'))
f.close()
def trtDOS(lig):
global numlig
lout=None
try:
if lig[:5].upper()=='CD /D':
os.chdir(ligin[5:].lstrip())
elif lig[:2].upper()=='CD':
os.chdir(ligin[2:].lstrip())
elif lig[0]=='.' :
lout=trtPYT(lig[1:])
else:
lout=cmdp([lig])
except:
lout='Error'
pass
return lout
def trtPYT(lig):
global numlig,pmode
lout=None
#echolf()
#print "lig:",lig
try:
if lig[0]=='.' :
lout=trtDOS(lig[1:])
else:
try:
try:
lout=eval(lig)
except:
exec(lig,globals(),globals())
except:
#msginfo("pb avec ponx:PRun')
#msginfo("Type_erreur: ",str(sys.exc_info()[0]))
#msginfo("Valeur erronnée: ",str(sys.exc_info()[1]))
tb=sys.exc_info()[2] #traceback
echoline("erreur dans EXEC")
echoline(str(sys.exc_info()[0]))
echoline(str(traceback.format_exc()))
#msginfo(str(sys.exc_info()[0]),traceback.format_exc())
except:
lout='Error'
return lout
def saimulti():
global numlig,maxlig,pmode,lin,lout,imacro,pmacro,gconsole,editor,conservout,conserverr
multi=[]
nb=1000
while 1:
nb+=1
gconsole.cprompt('Multi.'+str(nb)[1:]+'>')
if imacro>-1:
imacro+=1
if imacro>=len(pmacro):
imacro=-1
if imacro>-1:
lig=pmacro[imacro]
cod=None
time.sleep(0.1)
else:
lig,cod=sai()
echoline(lig)
if lig.upper()=='QUIT' or lig.upper()=='EXIT' or lig.upper()=='END':
break
multi.append(lig)
#echolist('\n'.join(multi)+'\n')
return '\n'.join(multi)+'\n'
#--------------------------------------mainloop---------------------------
def mainloop(repinitial='', macroinitial=None):
global numlig,maxlig,pmode,lin,lout,imacro,pmacro,gconsole,editor,conservout,conserverr
import consol
lin={}
lout={}
maxlig=250
numlig=-1
editor="notepad"
#editor="C:\Program Files\Windows NT\Accessoires\wordpad.exe"
#pmode='PYTHON'
pmode='DOS'
pmacro=[]
imacro=-1
class globa(object):
consoleprompt="AAA>"
tablistpersist=[]
tabprefixe=''
gconsole=consol.console()
if not flagponx:
#chargeponx()
chargepbridge()
if repinitial!='':
os.chdir(repinitial)
if macroinitial==None:
imacro=-1
else:
imacro=0
pmacro=macroinitial
while 1:
if numlig>maxlig:
lin={}
lout={}
numlig=-1
numlig+=1
gconsole.cprompt(os.getcwd()+'> pmode:'+str(pmode)+' lig:'+str(numlig)+' '+time.strftime("%d.%m %H:%M:%S", time.gmtime()))
if imacro>-1:
imacro+=1
if imacro>=len(pmacro):
imacro=-1
if imacro>-1:
ligin=pmacro[imacro]
cod=None
echolf()
echoprompt(ligin)
echolf()
else:
ligin,cod=sai()
ligout=None
try:
#while 1:
#print
#print "-------------------",pmode,'.'+ligin.upper()+'.'
if ligin.upper()=='QUIT' or ligin.upper()=='.Q' or ligin.upper()=='EXIT':
break
lin[numlig]=ligin
if ligin=='':
continue
if ligin[0]==':':
continue
if ligin[:2].upper()=='CD':
echoline(ligin)
echohr()
os.chdir(ligin[2:].lstrip())
continue
if ligin.upper()=='.MULTI':
echoline(ligin)
echohr()
ligin=saimulti()
lin[-1]=ligin
if ligin.upper()[:4]=='.DOS':
echoline(ligin)
echohr()
ligin='.PMODE(DOS)'
lin[-1]=ligin
if ligin.upper()[:4]=='.PYT':
echoline(ligin)
echohr()
ligin='.PMODE(PYTHON)'
lin[-1]=ligin
if ligin.upper()[:3]=='...':
echoline(ligin)
echohr()
runpymacro(ligin[3:])
continue
if ligin.upper()[:2]=='..':
echoline(ligin)
echohr()
runmacro(ligin[2:])
continue
if ligin[0]=='.' :
echoline(ligin)
echohr()
cde=ligin[1:].upper()
if cde=='UPDATE':
try:
pxd.recupfileweb("http://ponx.org/download/CD/PONX/pejbshell.py")
pxd.recupfileweb("http://ponx.org/download/CD/PONX/pejbshell.pyw")
pxd.recupfileweb("http://ponx.org/download/CD/PONX/consol.py")
pxd.recupfileweb("http://ponx.org/download/CD/PONX/consol.htm")
pxd.recupfileweb("http://ponx.org/download/CD/PONX/consol.css")
shutil.copyfile('c:\\pejbshell.py',str(sys.argv[0]))
shutil.copyfile('c:\\pejbshell.pyw',str(sys.argv[0]))
shutil.copyfile('c:\\consol.py',"c:\\ponx")
shutil.copyfile('c:\\consol.htm',"c:\\ponx")
shutil.copyfile('c:\\consol.css',"c:\\ponx")
os.remove('c:\\pejbshell.py')
os.remove('c:\\pejbshell.pyw')
os.remove('c:\\consol.py')
os.remove('c:\\consol.htm')
os.remove('c:\\consol.css')
echoline("UPDATE finished")
except:
msginfo("Problème","pour récupérer la dernière version.")
continue
if cde=='TEST':
test()
continue
pass
if cde=='EMPTY':
lin={}
lout={}
numlig=-1
continue
elif cde=='EDIT':
ltmp=[]
for i in range(1,numlig):
ltmp.append(lin[i])
txt='\n'.join(ltmp)
fichierw(txt)
#startfile(os.getcwd()+'\\temp.txt')
st='"'+editor+'" "'+os.getcwd()+'\\temp.txt"'
#os.system(st)
from subprocess import Popen
p=Popen(st, shell=False)
continue
elif cde=='OUTEDIT':
txt=bufferout(-1)
print 'aaa'
fichierw(txt)
print 'bbb'
#startfile(os.getcwd()+'\\temp.txt')
st='"'+editor+'" "'+os.getcwd()+'\\temp.txt"'
#os.system(st)
from subprocess import Popen
p=Popen(st, shell=False)
continue
elif cde=='OUTEDITU':
txt=bufferout(-1)
fichierwu(txt)
#startfile(os.getcwd()+'\\temp.txt')
st='"'+editor+'" "'+os.getcwd()+'\\temp.txt"'
#os.system(st)
from subprocess import Popen
p=Popen(st, shell=False)
continue
elif cde=='PMODE':
echoline('pmode : '+pmode)
continue
elif cde[:6]=='PMODE(':
if cde[6]=='D':
pmode='DOS'
else:
pmode='PYTHON'
echoline('pmode : '+pmode)
continue
if pmode=='DOS':
if ligin!='':
echoline(ligin)
echohr()
ligout=trtDOS(ligin)
elif pmode=='PYTHON':
if ligin!='':
echoline(ligin)
echohr()
ligout=trtPYT(ligin)
else:
ligout=None
if ligout:
lout[numlig]=ligout
echo(ligout)
except:
echoline('Error (mainloop)')
pass
gconsole.close()
time.sleep(0.3)
if __name__=='__main__':
if len(sys.argv)>1:
rep=sys.argv[1]
else:
rep='C:\\'
mainloop(rep)