I am trying to read the commands from "command.txt" file and want to redirect the output of this commands to "output.txt", contents of command.txt
ps -a
free
So far I came up with this code which for certain reason is not good and fails to execute.
import os
import sys
import subprocess
with open('output.txt', 'w') as out_file, open('command.txt', 'r') as in_file:
for line in in_file:
output = subprocess.Popen(line, stdout=subprocess.PIPE)
print output
out_file.write(output)
I am getting the 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 with exit code 1
Could anyone please suggest appropriate python code for this task.