(Courriels de diversion: <empresserai@recueillirent-inspecterent.com> <negocies@lunaire-decuver.com> <fastueux@militaient-resisteras.com> <faconnier@exponentielles-antagoniste.com> <implorerent@consisteriez-admissibilites.com> <commotionne@appuyait-cuisinerez.com> <depreciatifs@totalitaires-deposeras.com> <integrales@hoteliere-equatoriales.com> <insurgeras@parfaire-hacher.com> <deculpabilisent@disconvienne-optimaliser.com> )



De ce que j'en ai compris, le p.poll() sert à mettre à jour le champ
valeur de retour de l'objet p.


Pour être plus précis:

«Popen.poll()¶
<http://docs.python.org/library/subprocess.html#subprocess.Popen.poll>
    Check if child process has terminated. Set and return returncode
    <http://docs.python.org/library/subprocess.html#subprocess.Popen.returncode>
    attribute.»

http://docs.python.org/library/subprocess.html


1/ pour que subprocess.Popen soit bloquant ?

Ce que je fais: je le lance en non-bloquant, et je met juste après une boucle qui attend que la valeur de retour soit positionne, avec une pause d'une seconde dans la boucle, pour ne pas consommer toute la CPU. Ce n'est sans doute pas la bonne méthode, car cela fait perdre jusqu'à une seconde pour chaque appel à un process.

Je crois que l'extrait suivant de la documentation répond aussi à la question:

«Replacing os.system()¶
<http://docs.python.org/library/subprocess.html#replacing-os-system>

sts = os.system("mycmd" + " myarg")
==>
p = Popen("mycmd" + " myarg", shell=True)
sts = os.waitpid(p.pid, 0)

Notes:

    * Calling the program through the shell is usually not required.
    * It’s easier to look at the returncode attribute than the exit status.

A more realistic example would look like this:

try:
    retcode = call("mycmd" + " myarg", shell=True)
    if retcode < 0:
        print >>sys.stderr, "Child was terminated by signal", -retcode
    else:
        print >>sys.stderr, "Child returned", retcode
except OSError, e:
    print >>sys.stderr, "Execution failed:", e

»
http://docs.python.org/library/subprocess.html

Un autre élément de réponse pourrait être le suivant:


      «Convenience Functions¶
      <http://docs.python.org/library/subprocess.html#convenience-functions>

This module also defines two shortcut functions:

subprocess.call(/*popenargs/, /**kwargs/)¶
<http://docs.python.org/library/subprocess.html#subprocess.call>

    Run command with arguments. Wait for command to complete, then
    return the returncode attribute.

    The arguments are the same as for the Popen constructor. Example:

    retcode = call(["ls", "-l"])
        

subprocess.check_call(/*popenargs/, /**kwargs/)¶
<http://docs.python.org/library/subprocess.html#subprocess.check_call>

    Run command with arguments. Wait for command to complete. If the
    exit code was zero then return, otherwise raise CalledProcessError.
    The CalledProcessError object will have the return code in the
    returncode attribute.

    The arguments are the same as for the Popen constructor. Example:

    check_call(["ls", "-l"])
        

    New in version 2.5.»

http://docs.python.org/library/subprocess.html



2/ pour que subprocess.Popen me renvoie le résultat de la ligne de
commande (et non pas le pid)

Si par résultat de la ligne de commande, on entend les quelques bits du
code de retour,


Il me semble qu'il s'agit de l'attribut returncode de l'objet p (the
returncode attribute).


«Popen.returncode¶
<http://docs.python.org/library/subprocess.html#subprocess.Popen.returncode>

    The child return code, set by poll()
    <http://docs.python.org/library/subprocess.html#subprocess.Popen.poll>
    and wait()
    <http://docs.python.org/library/subprocess.html#subprocess.Popen.wait>
    (and indirectly by communicate()
    <http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate>).
    A None value indicates that the process hasn’t terminated yet.

    A negative value -N indicates that the child was terminated by
    signal N (Unix only).»


Si par résultat de la ligne de commande, on entend un flux comme le
stdout, il faut vraisemblablement utiliser des pipes, à moins d'utiliser
(pour les flux de taille limitée):Popen.communicate(/input=None/)¶
<http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate>





Jean-Marc Mongrelet a écrit :

> Salut Jean-Michel,
>
> Effectivement, ça fonctionne plutôt bien!
>
> Je me demande, à quoi sert le p.poll()... si je le commente, je ne
> constate aucun changement.
>
> Puisque tu m'as l'air de bien connaitre, puis-je te demander quelques
> conseils...
> 1) comment faire pour que subprocess.Popen soit bloquant ?
> 2) comment faire pour que subprocess.Popen me renvoie le résultat de la
> ligne de commande (et non pas le pid) ?
>
> Si j'ai les réponses 1 et 2, je peux définitivement me passer de
> os.popen qui est en phase de devenir obsolète, par subprocess.Popen sont
> semble t-il successeur!
>
> JM
>
>
> Jean-Michel a écrit :
>   
>> import subprocess
>>     
>>> def inPlayerList():
>>>         global PARAMETRE
>>>         if PARAMETRE.has_key('nf') :
>>>                 #Multimedia.MULTIMEDIA.set_Baffle(PARAMETRE['nf'])
>>>                 os.popen('amarok -a "%s"'%(PARAMETRE['nf']), 'w', 0)
>>>         if PARAMETRE.has_key('ss') :
>>>                 #Multimedia.MULTIMEDIA.set_Casque(PARAMETRE['ss'])
>>>                 print '%s "%s" &'%(Commun.config_txt('xmms'),PARAMETRE['ss'])
>>>                 #x = os.popen('%s "%s" &'%(Commun.config_txt('xmms'),PARAMETRE['ss']))
>>>                 p = subprocess.Popen(args = '%s "%s" &'%(Commun.config_txt('xmms'),PARAMETRE['ss']), shell=True, close_fds=True)
>>>       
>
>   
>>>                 p.poll()
>>>                 print "exec ss done pid = " + str(p.pid)
>>>                 #x.close()
>>>                 print "close done"
>>>                 PARAMETRE['cs'] = PARAMETRE['ss']
>>>
>>>       
>
>   


-----------------------------------------------------------------
Les listes de diffusion du CULTe - Pour une informatique libre
http://www.CULTe.org/listes/
Pour se desabonner:
mailto:linux-31-unsubscribe@CULTe.org?subject=Cliquez_sur_ENVOYER