Python Forum
Writting system comand into a file. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Writting system comand into a file. (/thread-3503.html)



Writting system comand into a file. - Mike Ru - May-29-2017

How can I write it into file?
I have a script
import os
os.system('ls')
I need to put output of this script into file.txt.
How can I do it?


RE: Writting system comand into a file. - wavic - May-29-2017

In the console:
python3 my_script.py >> file.txt
This is called redirection. Instead of the standard output for any command ( stdout ) the output from the command is redirected to a file using >>
A single > writes to a file. If the file exists it will be overwritten. >> appends to a file. Both will create the file if it doesn't exist.


RE: Writting system comand into a file. - snippsat - May-29-2017

Mike Ru Wrote:How can I write it into file?
I have a script
os.system is deprecated,use subprocess.
For Python 2.7 or newer versions can use check_output(),to cacth the output.
Example:
from subprocess import check_output

# Windows
out = check_output(['ping', 'google.com'])
# linux
#out = check_output(['ping', '-c', '4', 'google.com'])
print(out.decode('utf-8').strip())
Output:
Pinging google.com [108.177.14.102] with 32 bytes of data: Reply from 108.177.14.102: bytes=32 time=63ms TTL=48 Reply from 108.177.14.102: bytes=32 time=64ms TTL=48 Reply from 108.177.14.102: bytes=32 time=63ms TTL=48 Reply from 108.177.14.102: bytes=32 time=63ms TTL=48 Ping statistics for 108.177.14.102:    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds:    Minimum = 63ms, Maximum = 64ms, Average = 63ms