bladexeon
bladexeon

Reputation: 706

Python Subprocess storing call output to file

I've tried methods that I have seen without luck and the Docs dont say much about storing the Output. I've tried the below:

import subprocess
f = open(r'/var/log/temp.txt','w')
subprocess.call('cd /var/log/messagelog', shell=True, stdout=f)
f.close()
with open("/var/log/temp.txt",'r') as f:
    for line in f:
            print line

All I'm trying to do is get the program to recognize that the directory does not exist. ive substituted a simple print statement for the time being. i CANNOT use check_output for this as updating Python on 30 different systems is highly impractical for this. print line should produce: "cd: can't cd to /var/log/messagelog". Hoping this is a rookie mistake I am making here so another set of eyes here would be greatly appreciated.

EDIT: All I'm trying to do here is see if the directory exists and if not, then create the directory. There may be other ways of doing this but everything I've seen points to subprocess. cd is not a program hence why i have to use call instead of Popen.

Upvotes: 0

Views: 136

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180522

use the os module to check if the directory exists and to create it if it does not potential race condition:

import os
if not os.path.isdir('/var/log/messagelog'):
    os.mkdir('/var/log/messagelog')

You can also just try to create it and check for specific error:

import os
try:
    os.mkdir(path)
except OSError as e:
    if e.errno == 17:
        print("dir exists")
    else:
         raise 

You can use the EEXIST constant if it makes it more readable:

import errno
import os

try:
    os.mkdir(path)
except OSError as e:
    if errno.EEXIST == e.errno:
        print("dir exists")
    else:
        raise 

This will only catch a directory exists error, any other OSError will be raised which may or may not be what you want.

Upvotes: 4

oz123
oz123

Reputation: 28878

You should use

proc = sp.Popen(..., stdout=filehandle)
err = proc.communicator()

Instead of sp.call. The output will be in the out.

Check the docs.

Upvotes: 0

Related Questions