简体   繁体   中英

It does print output but why it is not writing in file?

import subprocess
f = open("sum.txt","a")
def execute(cmd):
        popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
        for stdout_line in iter(popen.stdout.readline, ""):
            yield stdout_line 
        popen.stdout.close()
        return_code = popen.wait()
        if return_code:
            raise subprocess.CalledProcessError(return_code, cmd)




for uses in execute(['ls','-ltr']):
    f.write(uses)
    print(uses)

You need to close the file after writing to it after the for loop has completed

for uses in execute(['ls','-ltr']):
    f.write(uses)

f.close()

This is safer in a try ... finally block as it will close the file even if there is an error when performing operations on the file.

try:
    f = open("sum.txt","a")
    for uses in execute(['ls','-ltr']):
        f.write(uses)
finally:
    f.close()

Or better yet, using the with statement as this will close the file once the statement has executed

with open("sum.txt","a") as f:
    for uses in execute(['ls','-ltr']):
        f.write(uses)

You should use the context-manager to open a file. With this solution your file will be closed.

Code:

import subprocess


def execute(cmd):
        popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
        for stdout_line in iter(popen.stdout.readline, ""):
            yield stdout_line
        popen.stdout.close()
        return_code = popen.wait()
        if return_code:
            raise subprocess.CalledProcessError(return_code, cmd)


with open("sum.txt", "a") as opened_file:
    for uses in execute(['ls', '-ltr']):
        opened_file.write(uses)
        print(uses)

Output:

>>> python3 test.py 
total 96

-rw-rw-r-- 1 milanbalazs users  637 Jul 29 12:30 README.md

drwxrwxr-x 4 milanbalazs users 4096 Jul 29 12:30 admin

-rwxrwxr-x 1 milanbalazs users 1706 Jul 29 12:30 bash_unit_test.sh

The content of sum.txt file is same.

To avoid these type of errors, use with open() in code. It will automatically close the file.

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