Sumit Duwal
Sumit Duwal

Reputation: 55

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)

Upvotes: 1

Views: 109

Answers (3)

Mikey Lockwood
Mikey Lockwood

Reputation: 1261

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)

Upvotes: 1

Arun Augustine
Arun Augustine

Reputation: 1766

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

Upvotes: 0

milanbalazs
milanbalazs

Reputation: 5329

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.

Upvotes: 1

Related Questions