-1

so i found this on how to call an external command from python, but how do i use this method, but output the output of the command into an external file. So essentially i need the output of the command to be stored as a text file. Is this possible? i can't find much info on how to do this, and the ones i have found have not been clear

this is my current code, but it just displays the output on the screen and i have no idea how i would store it as a file

    #!/usr/bin/python
## get subprocess module 
import subprocess

## call date command ##
p = subprocess.Popen("date", stdout=subprocess.PIPE, shell=True)

## Talk with date command i.e. read data from stdout and stderr. Store this info in tuple ##
## Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached.  ##
## Wait for process to terminate. The optional input argument should be a string to be sent to the child process, ##
## or None, if no data should be sent to the child.
(output, err) = p.communicate()

## Wait for date to terminate. Get return returncode ##
p_status = p.wait()
print "Command output : ", output
print "Command exit status/return code : ", p_statu
ItsMeNaira
  • 360
  • 1
  • 12
  • first, drop shell=True, then maybe you'd need to redirect `stderr=subprocess.PIPE` too just in case the process writes to standard error. Then drop python 2. – Jean-François Fabre Mar 19 '20 at 21:43
  • Please clarify what the issue is. – AMC Mar 20 '20 at 02:55
  • @AMC I saw that post on how to call an external command in python, and I know how to display the the result of the command. But I wanted the result of the command to be saved in a file – ItsMeNaira Mar 20 '20 at 02:57
  • @ItsMeNaira Isn’t that already what you wrote in your question? I was asking for something more specific. Have you tried breaking down the task, for example, or written any pseudocode? – AMC Mar 20 '20 at 03:04

2 Answers2

1

You can use system from os.

import os
os.system("ls -l > file.txt")

Writing the output of a command can be accomplished by ">". If you want to append instead of overwriting the file, you can use ">>".

Seleme
  • 241
  • 1
  • 8
  • They can, but why should they? Isn’t the use of `os.system()` discouraged in favour of the Subprocess module? – AMC Mar 20 '20 at 02:56
0

This will do what you're asking :

import subprocess
with open ('date.txt', 'w') as file :
    subprocess.Popen ('date', stdout = file)
bashBedlam
  • 1,402
  • 1
  • 7
  • 11