How to write an output of a command to stdout and a file in Python3?

2024/11/15 20:04:44

I have a Windows command which I want to write to stdout and to a file. For now, I only have 0 string writen in my file:

#!/usr/bin/env python3
#! -*- coding:utf-8 -*-import subprocesswith open('auto_change_ip.txt', 'w') as f:print(subprocess.call(['netsh', 'interface', 'show', 'interface']), file=f)
Answer

subprocess.call returns an int (the returncode) and that's why you have 0 written in your file.
If you want to capture the output, why don't you use subprocess.run instead?

import subprocesscmd = ['netsh', 'interface', 'show', 'interface']
p = subprocess.run(cmd, stdout=subprocess.PIPE)
with open('my_file.txt', 'wb') as f:f.write(p.stdout)

In order to capture the output in p.stdout, you'll have to redirect stdout to subprocess.PIPE.
Now p.stdout holds the output (in bytes), which you can save to file.


Another option for Python versions < 3.5 is subprocess.Popen. The main difference for this case is that .stdout is a file object, so you'll have to read it.

import subprocesscmd = ['netsh', 'interface', 'show', 'interface']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out = p.stdout.read()
#print(out.decode())  
with open('my_file.txt', 'wb') as f:f.write(out)
https://en.xdnf.cn/q/119282.html

Related Q&A

Mongodb adding a new field in an existing document, with specific position

I am facing this issue where I need to insert a new field in an existing document at a specific position. Sample document: { "name": "user", "age" : "21", "…

how to check every 3 x 3 box in sudoku?

I am trying to build a sudoku solver without much googling around. Right now, I am working on a function to test whether the board is valid, which I will use later in a loop. This is what the function …

multiple model accuracy json result format using python

I am building a multiple model and i am getting results with 7 models accuracy, i need those results with a proper json format.My multiple model building code will be like thisseed = 7"prepare mod…

Calculate Time Difference based on Conditionals

I have a dataframe that looks something like this (actual dataframe is millions of rows):ID Category Site Task Completed Access Completed1 A X 1/2/22 12:00:00AM 1/1/22 12:00:00 AM1 A Y 1/3/22 12:00:00A…

Cannot open jpg images with PIL or open()

I am testing to save ImageField in Django, but for some reason all the *.jpg files Ive tried dont work while the one png I had works. Using django shell in WSL VCode terminal. python 3.7 django 3.0 pil…

how to delete tensorflow model before retraining

I cant retrain my image classifier with new images, I get the following error:AssertionError: Export directory already exists. Please specify a different export directory: /tmp/saved_models/1/How do I …

Use beautifulsoup to scrape a table within a webpage?

I am scraping a county website that posts emergency calls and their locations. I have found success webscraping basic elements, but am having trouble scraping the rows of the table. (Here is an example…

Encrypt folder or zip file using python

So I am trying to encrypt a directory using python and Im not sure what the best way to do that is. I am easily able to turn the folder into a zip file, but from there I have tried looking up how to en…

Use Python Element Tree to parse xml in ASCII text file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Time series plot showing unique occurrences per day

I have a dataframe, where I would like to make a time series plot with three different lines that each show the daily occurrences (the number of rows per day) for each of the values in another column. …