Skip to main content

PathGetter - 6.3

a function to browse the files and returns a path.


josmiley / Luke spywoker
(mutualaccount)

This is a function that allows the user to enter a valid file path like in a file browser.
It returns a string.
Browse with mouse or keyboard. It supports tab-completion.
You can also display a resizable and rotatable image preview.

Usage is very simple:
     In a python script: PathGetter(path='',mode=None,caption='Path Getter')

mode = None ==> any path
mode = 1 ==> file path
mode = 2 ==> directory path

The code is executed in a separated window using the subprocess module.
Therefore, it's independent of the size of your window.

see example_pathgetter.py for example

thanks to Jouni Järvinen and spacemax for testing and optimization.


Links

Home Page
http://joel-murielle.perso.sfr.fr
Source
http://joel-murielle.perso.sfr.fr/PathGetter.zip

Releases

PathGetter 6.1 — 11 Jun, 2011

PathGetter 6.2 — 12 Jun, 2011

PathGetter 6.4 — 23 Jun, 2011

PathGetter 6.0 — 30 May, 2011

PathGetter 6.3 — 22 Jun, 2011

PathGetter 6.6 — 2 Jul, 2011

PathGetter 6.5 — 1 Jul, 2011

Pygame.org account Comments

  • Avirup Kundu 2011-05-08 17:26:00

    Traceback (most recent call last):

    File "C:\Documents and Settings\AVi\My Documents\Downloads\pygamebrowser\pygamebrowser\test.py", line 4, in <module>

    img = image.load(pygamebrowser.browse(mode=1))

    pygame.error: SDL_RWFromFile(): No file or no mode specified

    Why am i getting this error?? I ran the 2to3 script on the files.. I am using python 3.1

    josmiley 2011-05-10 08:11:47

    normally the bug has been fixed

  • R Sievers 2011-05-09 15:06:29

    This looks promising :-)

    Would I be able to use it inside of a GPL3 application?

    josmiley 2011-05-10 07:07:18

    hi, GPL3 shall be applicable to all my projects

    .

  • Cnoffsin 2011-05-10 16:35:53

    thumbnail viewer. Nice!

  • Hairo R. Carela 2011-05-11 18:22:16

    Could you add keyboard support??

    josmiley 2011-05-11 18:48:39

    folderbox and filebox doesn't support keyboard but you can type a path in pathbox

    Hairo R. Carela 2011-05-11 19:05:27

    Ohh, thanks...

  • Jouni Järvinen 2011-05-15 00:24:07

    You should use the PRINT statement as a Function instead even if you use Py v2.x; print(...)

    Py v3.1 & PyGame 1.9.1, doesn't work.
    -----------------------------------------------------
    C:\Users\rautamiekka\Desktop\GetPath>c:\Python32\python.exe GetPath.py
      File "GetPath.py", line 228
        else: print 'remain to do'
                                 ^
    SyntaxError: invalid syntax
    <fixed>
    C:\Users\rautamiekka\Desktop\GetPath>c:\Python32\python.exe GetPath.py
    Traceback (most recent call last):
      File "GetPath.py", line 4, in <module>
        from lib.PygameReadWrite import reader,form
      File "C:\Users\rautamiekka\Desktop\GetPath\lib\PygameReadWrite\reader.py", line 246
        print txt.WORD
                ^
    SyntaxError: invalid syntax
    <fixed>
    C:\Users\rautamiekka\Desktop\GetPath>c:\Python31\python.exe GetPath.py
    Traceback (most recent call last):
      File "GetPath.py", line 4, in <module>
        from lib.PygameReadWrite import reader,form
      File "C:\Users\rautamiekka\Desktop\GetPath\lib\PygameReadWrite\form.py", line 262
        print txt.OUTPUT
                ^
    SyntaxError: invalid syntax
    <fixed>
    C:\Users\rautamiekka\Desktop\GetPath>c:\Python31\python.exe GetPath.py
    Traceback (most recent call last):
      File "GetPath.py", line 300, in <module>
        aaa = Browser(path)
      File "GetPath.py", line 159, in __init__
        self._path = os.getcwdu() if not path or not os.path.isabs(path) else path
    AttributeError: 'module' object has no attribute 'getcwdu'
    <can't continue="">

  • Jouni Järvinen 2011-05-15 00:24:39

     Stupid comment system ...

    josmiley 2011-05-15 03:58:09

     thanks, effectively, I used sys.stdout.write() to resolve this problem and I think it should work now.

  • Jouni Järvinen 2011-05-15 11:15:26

    Good work, AFAIS, works fine now with Py v3.1 / PyGame 1.9.1 !

    josmiley 2011-05-15 11:58:21

     thank you for testing ;)

  • Jouni Järvinen 2011-05-23 21:24:02

    PathGetter 4.8 functions as well !

    The "format()" Function is faster alternative to concatinating string with the "+" although it needs more coding: >http://docs.python.org/library... notice, that to be compliant with Python v2.6 and any version since that without repeating same in the string, you must put a number inside the brackets.

    Python supports the use of "^=" operator which is faster doing the thing than "VAR=VAR^1", just like "+=" is faster than "VAR=VAR+1".

    Since the "while" statement will only run if the expression resolves into truth, and that "True" already equals 1 after around-the-corner resolving, "while True" can be replaced with "while 1" for small added speed.

    josmiley 2011-05-24 08:27:20

    hi,
    thanks for tricks, but i don't see where i can use str.fotmat() in the code ... ?
    i think at line 17 ( self.text = ' '+'\n '.join(liste)+'\n' ) but how ?

    Jouni Järvinen 2011-05-24 11:23:15

    In v4.9 ...

    - Line 17: self.text = " \n{0}\n".format("".join(liste))
    - Line 35: self.text = " \n{0}\n".format("".join(liste))

    josmiley 2011-05-24 12:18:57


    i 've tried with
    self.text = ' {0}\n'.format('\n '.join(liste))
    but it raises an UnicodeEncodeError (python 2.7)
    then i've tried like this
    self.text = ' %s\n'%'\n '.join(liste)
    and it seems that it works

    Jouni Järvinen 2011-05-24 13:49:25

    I'm completely new to that error but I do know the French language's accented letters cause it. You could ask over at http://stackoverflow.com for a solution.

    Sure you can continue using the "%" operator since it's faster than concatenation and it works for your case.

  • spacemax 2011-05-24 05:36:30

    Salut jo,

    Certaines images se cachent lorsqu'on clic sur le bouton image only. Le processeur est par ailleurs beaucoup sollicité. Sinon encore un petit effort et Nautilus n'aura qu'à bien se tenir ! Beau travail.

    josmiley 2011-05-24 08:51:24

    salut max,

    effectivement, e vois aussi grace à tes screen un autre bug; le nom du fichier disparait de la barre du haut quand on déchoche 'images only'. Bon, ça c'est corrigé ...

    Peux-tu m'envoyer ton image "Microsoft_Windows_XP_Gold.jpg"; c'est bizard que imghdr la zappe.
    joel-murielle sfr.fr

    Nautilus n'a rien à craindre ^^, c'est pas un filebrowser que je fais.
    c'est une interface, qui évite à l'utilisateur de ton programme, de taper un chemin à la main.
    genre, tu demandes à l'utilisateur s'il veut enregistrer ou charger un fichier, par exemple son profile, mais tu lui laisses le choix de l'emplacement et du nom. Soit tu codes une boite de dialogue qui lui demande de saisir le chemin complet, soit tu utilises mon code.

    exemple:
    >>rep = raw_input('ouvrir une image ? ')
    >>if rep == 'o':
    . . . .    chemin = PathGetter.get()
    . . . .    pygame.image.load('chemin')

    merci pour le feedback.

  • Jouni Järvinen 2011-05-24 11:39:37

    Since the "hidden files (unix)" is literally only for *NIX systems, the program should check on which system it is being run. Myself I can test Window$ & Linux, for which I know that the "platform()" from module "platform" will tell 'Windows' & 'Linux'. I found out that MacOS X will report 'Darwin'. In else case the program should just show the option so the users of other systems will know to tell by experience whether it works.

    josmiley 2011-05-24 15:28:28

    good reasoning
    now under Windows, 'hidden files' does not appear (line 176)
    I await testing under other systems

    thanks.

    Jouni Järvinen 2011-05-24 11:44:46

    PS. The result of the mentioned Function is a string, so something like the below makes it easier to safely compare. I think it's better to blacklist the unsupported systems than whitelisting the supported ones.

    if not "WINDOWS" or ... in platform().upper()

  • spacemax 2011-05-25 08:06:25

    Salut jo,
    Impossible d'envoyer l'image par mail. Je la mets ici. Les png que tu as mis dans le zip n'ont pas de miniatures voir capture écran. 
    Et toujours le process à 100%. J 'ai ajouté  un wait dans ta boucle :
    while run:
            time.wait(50)
    a+

    josmiley 2011-05-25 16:51:22

    finalement j'ai remis imghdr car les temps de chargement devenaient trop long, mais j'ai trouvé une combine qui devrait faire l'affaire.
    j'ai encore optimisé le rendu pour limiter l'utilisation du processeur.

    spacemax 2011-05-25 18:03:35

    nouvelle version testée. ok pour l'image Microsoft_Windows_XP_Gold.jpg, ok pour le processeur mais toujours pas de miniatures pour les fichiers livrés (button.png button0.png button1.png) dans le répertoire images alors que d'autres png sur mon disque ont une miniature. Peut-être un problème de version ?
    Sinon, une amélioration sympa serait de mettre en gras ou en surlignage les fichiers sélectionnés.
    a+

    josmiley 2011-05-25 20:44:49

    bonne idée pour le highlighting, mais j'aidu mal à harmoniser les couleurs; j'espère que ça reste lisible.
    sinon pour les images qui s'affichent pas ... hum, tu es sous xfce ?
    je vais installer cette distro pour voir .... je sais par experience que fût un temps, des images fesaient planter thunar.

    spacemax 2011-05-28 13:38:31

    Salut Joe,

    Je ne suis pas sous Thunar mais sous  Nautilus 2.30.1 Debian Squeeze noyau 2.6.32-5-686.
    Mes images png sont bien traitées et la miniature et affichée..Je te joins les captures.
    Un bug : quand on clique sur hidden files le nom disparaît dans la barre d'adresse.

    Pour les png, ça m'intrigue...

    spacemax 2011-05-28 13:40:49

    Un bug : quand on clique sur hidden files le nom disparaît dans la barre d'adresse ainsi que la miniature

    josmiley 2011-05-28 18:43:07

    merci max
    c'est corrigé.

    pour les images incluses, je les ai reconverties avec un autre soft que gimp; peut-être que ça fonctionne maintenant.

    spacemax 2011-05-28 19:57:48

    Hé Hé...
    Le problème vient des accents dans les répertoires : pas de miniatures si accents dans le chemin !
    A corriger Jo.

    josmiley 2011-05-28 22:12:57

    bien vu !

    mais je crois que le bug vient de pygame
    en effet image.load() semble ne pas géré les chaine unicode accentuée

    (peut-être qu'en passant par IOstring ... hum, ça me semble un peu barbare ^^)

    spacemax 2011-06-04 21:13:20

    salut joe,

    Avec la 6.0, j'obtiens l'erreur suivante si des caractères accentués sont présents dans le chemin :
    /usr/lib/python2.6/dist-packages/pygame/sysfont.py:139: DeprecationWarning: os.popen3 is deprecated.  Use the subprocess module.  flin, flout, flerr = os.popen3('fc-list : file family style')Traceback (most recent call last):  File "PathGetter.py", line 391, in <module>    aaa.update(ev)  File "PathGetter.py", line 263, in update    if self.showviewer.status: self.load_image()  File "PathGetter.py", line 206, in load_image    f.name = ''AttributeError: can't set attribute

    J'ai modifié la fonction qui retourne le chemin en testant la plateforme Windows / Linux comme suit en convertissant en unicode pour Linux. Test Windows / Linux OK. A voir sur Mac.
        def load_image(self):                if OS!="WINDOWS":                         self.stringpath.OUTPUT=self.stringpath.OUTPUT.encode("utf-8")        if os.path.isfile(self.stringpath.OUTPUT) and imghdr.what(self.stringpath.OUTPUT):            try: self.viewer.IMAGE = image.load(self.stringpath.OUTPUT)            except:                with FileIO(self.stringpath.OUTPUT) as f:                    f.name = ''                    self.viewer.IMAGE = image.load(f)                        else: self.viewer.IMAGE = None

    A+

    josmiley 2011-06-05 22:03:52

    salut max,
    effectivement c'est un problème de version de python; 2.6 ne supporte pas unicode en natif
    mais je ne pense pas rétrocompatibiliser plus, car ça a déjà été un gros boulot pour faire tourner sur 2.7, 3, linux et windows ^^ .

    je te remercie encore car tu m'as beaucoup aidé. C'est très motivant lorsqu'il y a des personnes pour tester nos codes et qui sont intéressées par notre travail. J'espère te rendre la pareil pour tes prochains projets.

    ++

    josmiley 2011-05-25 13:02:56

    merci max,
    il semble que ce soit imghdr qui pose problème, je l'ai donc retiré.

    j'ai un peu optimisé la boucle, je pense que la charge est maintenant acceptable, tout en gardant une bonne fluidité de l'affichage.

  • Jouni Järvinen 2011-05-26 07:29:40

    You certainly don't idle. But ...

    Lines 373-374 can be replaced by (without the law signs)
    §                if (mode == 2 and os.path.basename(aaa.OUTPUT)) or (mode == 1 and not os.path.basename(aaa.OUTPUT)): aaa.valid.ACTIV = False§

    Lines 378-386 can be replaced by (without the law signs)
    §                    if mode == None or (mode == 1 and os.path.basename(aaa.OUTPUT)) or (mode == 2 and not os.path.basename(aaa.OUTPUT)):
                            stdout.write(aaa.OUTPUT)
                            run = False§

    I don't see why you'd repeat the code which brings you the same result.

    josmiley 2011-05-26 11:30:05

    effectively ... thank.
    this is fixed.

  • Jouni Järvinen 2011-05-29 10:17:41

    v5.7 ...

    Lines 400-408 can be replaced by

    §                    if mode == None or (mode == 1 and os.path.basename(aaa.OUTPUT)) or
    (mode == 2 and not os.path.basename(aaa.OUTPUT)):

                            stdout.write(aaa.OUTPUT)

                            run = False§

    Lines 76-77 can be replaced by
    §        self.labelimage = Button.font.render(self.label,1,(255,255,255) if value else (100,100,100))§

    josmiley 2011-05-29 13:56:18

    thanks, some lines in less.

    no problem with cStringIO under windows ?

  • Jouni Järvinen 2011-05-29 19:21:05

    §import io§ works for me on Win7-64 with Python v2.7.1 x86 & PyGame v1.9.2pre. I were LANning the entire day so I couldn't check up Thunderbird. What to change in PathGetter v5.8 so I can test out cStringIO ?

    josmiley 2011-05-30 07:52:46

    it's okay
    pygame does not support accented unicode string but i find a trick to fix it (lines 205-207)

  • Jouni Järvinen 2011-05-30 10:18:48

    Now this is interesting: having "preview" on and trying to Backspace one letter after doing it on a "\", the program quits with error:
    ---------------------
    Traceback (most recent call last):
      File "PathGetter.py", line 394, in <module>
        aaa.update(ev)
      File "PathGetter.py", line 307, in update
        if self.showviewer.status: load_image()
    NameError: global name 'load_image' is not defined
    ---------------------
    Like in my case the program starts in folder "C:\Users\rautamiekka\Desktop\PathGetter\", taking away the "\" from "PathGetter\" works but then that erros raises when trying to take away the "r" from "PathGetter". This happens with both v2.7.x and v3.x installations.

    Next thing: try copying or cutting the path replaces the path with a box character, rendering the whole program frozen (unable to shutdown from the X in right top corner (though the button does react) and by the buttons in the program). If you write "\" with or without anything before it the program simply shuts down without notice or error.

    josmiley 2011-05-30 10:28:42

    oops ...fixed, "self" was missing.
    if self.showviewer.status: self.load_image()

    josmiley 2011-05-30 13:56:24

    it seems that windows needs "display.quit()" at the end of the code. fixed.

  • Jouni Järvinen 2011-05-30 21:50:32

    I didn't find any problems in v6.0 :) Though, there is code repeation: lines 249-250 can be replaced by

    §        if (ev.type == MOUSEMOTION and not any(ev.buttons)) or (self.showviewer.status and self.viewer.update(ev)): return§

    josmiley 2011-05-31 19:17:00

    thanks,
    i think it will be the final version

  • Jouni Järvinen 2011-06-12 16:21:37

    I didn't know you could actually do §       
    self.scr.blit(Coche.coche0,self) if self.status else 
    self.scr.blit(Coche.coche1,self)§ on line 106 but in case it doesn't you
    can do §        self.scr.blit(Coche.coche0 if self.status else
    Coche.coche1,self)§; Py reads each argument one-by-one from left to right separated by a comma, thus the brackets aren't needed like §        self.scr.blit((Coche.coche0 if self.status else
    Coche.coche1),self)§.

    As far as I've tested in two minutes, v6.1 has one issue [NOT TESTED WITH OLDER VERSIONS]: trying to access a file you have no permission for with the preview enabled, exits the program and gives this error. I was told instead of using §except: § you should specify each separate issue, like §except IOError: § and so on. Plus there can be unlimited count of §except§ keywords, so just simply using one solution for everything when it's possible to something completely diff' occur; even cases where one error is possible; http://c2.com/cgi/wiki?CatchWh.... So when there is no matching §except§, the program exits and prints the error, making it very much easier to debug the thing. I remember stepping onto such problem once where simply just §except: <do something="">§ was present and caused nice problems. You should read to better understand §try...except...else§: http://stackoverflow.com/quest...

    C:\Users\rautamiekka>python Desktop\PathGetter\PathGetter.py
    Traceback (most recent call last):
      File "Desktop\PathGetter\PathGetter.py", line 408, in <module>
        aaa.update(ev)
      File "Desktop\PathGetter\PathGetter.py", line 296, in update
        if self.showviewer.status: self.load_image()
      File "Desktop\PathGetter\PathGetter.py", line 200, in load_image
        if os.path.isfile(self.stringpath.OUTPUT) and imghdr.what(self.stringpath.OUTPUT):
      File "C:\Python27\lib\imghdr.py", line 12, in what
        f = open(file, 'rb')
    IOError: [Errno 13] Permission denied: u'C:\\Users\\rautamiekka\\ntuser.dat.LOG1'

  • Jouni Järvinen 2011-06-22 13:22:07

    v6.3 working fine and only one possible change in code: lines 392-394 replacable with §self.mem = False if not os.access(self._path,os.W_OK) or os.path.isfile(self._path) else True§.

    josmiley 2011-06-22 16:04:02

    thanks, fixed;
    you are definitively the champ of the optimization ;)

  • R Sievers 2011-06-26 09:55:33

    The module is really nice, but could you add the ability to display some explanation inside the PathGetter?
    I need the Users to select a source and a target directory. If would be really nice if he/she could easily determine the purpose of the PathGetter.

    If you don't want to add it to Mainline, could you give me a hint which source files I would need to tweak myself for my application?

    josmiley 2011-07-01 22:08:28

    I was not able to translate what you ask, my English is not very good.
    I added the argument "caption" that sets the window title.
    this answers there to your expectations?

    R Sievers 2011-07-02 13:06:32

    Yes it does :-)
    Thank you very much

    (my English probably isn't that good either ;-D )