Reading and writing from and to different files in Python -
i trying read commands "command.txt" file , want redirect output of commands "output.txt", contents of command.txt
ps -a free
so far came code reason not , fails execute.
import os import sys import subprocess open('output.txt', 'w') out_file, open('command.txt', 'r') in_file: line in in_file: output = subprocess.popen(line, stdout=subprocess.pipe) print output out_file.write(output)
i getting below error:
error: /system/library/frameworks/python.framework/versions/2.7/bin/python2.7/users/pythontutorials/subprocess1.py traceback (most recent call last): file "/users/shandeepkm/pythontutorials/subprocess1.py", line 9, in <module> output = subprocess.popen(line, stdout=subprocess.pipe) file "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/subprocess.py", line 709, in __init__ errread, errwrite) file "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/subprocess.py", line 1326, in _execute_child raise child_exception oserror: [errno 2] no such file or directory process finished exit code 1
could please suggest appropriate python code task.
solution 1: execute line line
you can redirect file using stdout
parameter of popen
:
import subprocess import shlex open('output.txt', 'wb') outfile, open('command.txt') infile: line in infile: command = shlex.split(line) if not command: continue # skip blank lines try: process = subprocess.popen(command, stdout=outfile) process.wait() except oserror: outfile.write('command error: {}'.format(line))
in code above, redirect output pointing stdout
output file's handle, no printing needed. code guard against bad commands
solution 2: call shell
if running under linux or mac, following solution simpler: calling bash execute whole command.txt file , record stdout , stderr. should work under windows cmd -c
, don't have windows machine try.
import subprocess open('output.txt', 'wb') outfile: command = ['bash', 'command.txt'] process = subprocess.popen(command, stdout=outfile, stderr=outfile) process.wait()
Comments
Post a Comment