简体   繁体   中英

saving subprocess output with tkinter

my code with subprocess:

def GO():
    my_sub=subprocess.Popen(['exe file','files in folder'],stderr=STADOUT,stdout=PIPE)\ 
    .communicate()[0]
    my_sub=my_sub.splitlines()
    for lines in my_sub:
       GO.a= lines
       print GO.a

In print GO.aa have:

1
2
3
4

In save button:

def save():
  type = [('file', '*.txt')]
  name = filedialog.asksaveasfile(type=ftypes, mode='w', defaultextension=".xxx")


  name.write(GO.a)
  name.close()

In saved file i have :

1

so only 1st line, not all lines

How to save them all, or all output from def GO() ?

EDIT: (after comments):

def GO():
    my_sub=subprocess.check_output(['exe file','files in folder'],stderr=STADOUT)
    output=my_sub.splitlines()
    for lines in output:
       GO.a= lines
       print GO.a

In save button output i am receiving only one line (last one 4 ) print GO.a works well, maybe i have something bad in save button section?

Try

def GO():
    my_sub=subprocess.Popen(['exe file','files in folder'],stderr=STADOUT,stdout=PIPE)\ 
    .communicate()[0]
    lines = my_sub.splitlines()
    GO.a = my_sub
    for line in lines:
       print line

assigning all the lines to the same variable does that, most of the time.

Popen is overkill for your current needs. It's useful when you want to interact with the subprocess in a more complex way.

To just get the output+error streams merged together, use check_output instead, for a simpler & shorter code. This function sets GO.a to the output splitted lines:

def GO():
    output = subprocess.check_output(['exe file','files in folder'], stderr=subprocess.STDOUT)
    GO.a = output.splitlines()

if you're using python 3 and you need text, use

GO.a = output.decode().splitlines()

instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM