Python Forum
Writting system comand into a file.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Writting system comand into a file.
#1
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?
Reply
#2
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  FileNotFoundError: [WinError 2] The system cannot find the file specified NewBiee 2 1,594 Jul-31-2023, 11:42 AM
Last Post: deanhystad
  Difference between os.system("clear") and os.system("cls") chmsrohit 7 16,661 Jan-11-2021, 06:30 PM
Last Post: ykumar34
  File system representation in a data structure Alfalfa 1 2,074 Dec-18-2019, 01:56 AM
Last Post: Alfalfa
Question Difference between Python's os.system and Perl's system command Agile741 13 6,863 Dec-02-2019, 04:41 PM
Last Post: Agile741
  Writting to file from if/else statement mcmxl22 2 1,878 Nov-19-2019, 06:23 PM
Last Post: mcmxl22
  writting python output to a csv file drifterf 1 1,714 Jul-19-2019, 04:07 AM
Last Post: micseydel
  Opening Directories on anothe File System mickrobinson567812 2 2,408 Apr-25-2019, 04:59 AM
Last Post: mickrobinson567812
  problems with writting a text file sunny 6 3,779 Feb-24-2019, 10:52 PM
Last Post: Larz60+
  Fatal Python error: Py_Initialize: unable to load the file system codec ecg1g15 0 3,582 Feb-12-2019, 12:16 PM
Last Post: ecg1g15
  subprocess error : The system cannot find the file specified evilcode1 0 10,716 Oct-03-2018, 08:04 AM
Last Post: evilcode1

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020