How to redirect the output of .exe to a file in python?

In a script , I want to run a .exe with some command line parameters as "-a",and then

redirect the standard output of the program to a file?

How can I implement that?


Asked by: Kimberly962 | Posted: 30-11-2021






Answer 1

You can redirect directly to a file using subprocess.

import subprocess
with open('output.txt', 'w') as output_f:
    p = subprocess.Popen('Text/to/execute with-arg',
                         stdout=output_f,
                         stderr=output_f)

Answered by: Elise455 | Posted: 01-01-2022



Answer 2

Easiest is os.system("the.exe -a >thefile.txt"), but there are many other ways, for example with the subprocess module in the standard library.

Answered by: Julian826 | Posted: 01-01-2022



Answer 3

You can do something like this e.g. to read output of ls -l (or any other command)

p = subprocess.Popen(["ls","-l"],stdout=subprocess.PIPE)
print p.stdout.read() # or put it in a file

you can do similar thing for stderr/stdin

but as Alex mentioned if you just want it in a file, just redirect the cmd output to a file

Answered by: Marcus778 | Posted: 01-01-2022



Answer 4

If you just want to run the executable and wait for the results, Anurag's solution is probably the best. I needed to respond to each line of output as it arrived, and found the following worked:

1) Create an object with a write(text) method. Redirect stdout to it (sys.stdout = obj). In your write method, deal with the output as it arrives.

2) Run a method in a seperate thread with something like the following code:

    p = subprocess.Popen('Text/to/execute with-arg', stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE, shell=False)
    while p.poll() is None:
        print p.stdout.readline().strip()

Because you've redirected stdout, PIPE will send the output to your write method line by line. If you're not certain you're going to get line breaks, read(amount) works too, I believe.

3) Remember to redirect stdout back to the default: sys.stdout = __sys.stdout__

Answered by: Daisy560 | Posted: 01-01-2022



Answer 5

Although the title (.exe) sounds like it's a problem on Windows. I had to share that the accepted answer (subprocess.Popen() with stdout/stderr arguments) didn't work for me on Mac OS X (10.8) with python 2.7.

I had to use subprocess.check_output() (python 2.7 and above) to make it work. Example:

import subprocess

cmd = 'ls -l'
out = subprocess.check_output(cmd, shell=True)
with open('my.log', 'w') as f:
    f.writelines(out)
    f.close()

Note that this solution writes all the accumulated output out when the program finishes. If you want to monitor the log file during the run. You may want to try something else. In my own case, I only cared about the end result.

Answered by: Joyce207 | Posted: 01-01-2022



Similar questions

Redirect bash output to python script

I am using zbarimg to scan bar codes, I want to redirect the output to a python script. How can I redirect the output of the following command: zbarimg code.png to a python script, and what should be the script like? I tried the following script: #!/usr/local/bin/python s = raw_input() print s I made it an executable by issuing the...


input - How to redirect output in different files in python

I am using the python script that takes two input files (goodProteins.fasta and list.txt) and save result in gene.fasta output files. fasta_file = "goodProteins.fasta" # First input wanted_file = "list.txt" # Second input result_file = "result.txt" # Output fasta file wanted = set() with open(wanted_file) as f: for line in f: line = line.strip() if line != "": wanted.add(...


bash - Redirect the output of a python script to THE BEGINNING of a file

I am aware of the following options to append the output to a file: test.py: print "Error" print "Warning" test.txt: Levels: Debug When I do: python test.py > test.txt It appends at the end of the file. However, if I want to append at the beginning of a file, so that the output of my file looks like as f...


Redirect print output to file in Python

I am trying to redirect print output to a file in Python 3.4 - right now as it stands my script prints to the shell. I don't really need it to do that. Here's my code: with open('Input.txt') as namelist: for line in namelist: line_lower = line.lower() a = namelist.readline() if fuzz.ratio(a, line) >= 95: print(fuzz.ratio(a, line)) print(a + ": " + line)...


I can't redirect output of a python file from a php call

I'm trying to execute a python file from php, in python file I have this: import sys from subprocess import PIPE, Popen nom = sys.argv[1]; print nom def cmdline(command): process = Popen( args=command, stdout=PIPE, shell=True ) return process.communicate()[0] cmdline("nmap x.x.x.x -oX sortida.xml") When I execute python pythonfile.py works, creat...


redirect output file from one python script as input file in another python script

I wrote a python script for file manipulations, Since I don't know the way to redirect output file from one python script as input file in another python script, I have to run both the scripts separately. I want to learn as to how to pass on the output file from one script as input file for another script. Can someone please guide me regarding this query?


Redirect the output of python script into a text file

This question already has answers here:


linux - Output redirect for python

I have python code that looks like this: cmd = './job1' print(cmd) os.system(cmd) If I run this, the output looks like: ./job1 done. But if I run it with output re-direct, say: python mycode.py > out1.log then 'out1.log' looks like this: done. ./job1 basically, if I run the python code using output redirect...


Redirect output to two files in python

I am writing code where i want to redirect output two different files in python one for log purpose and another for fabric code creation. Below is the code which redirect output to two different files: import sys print('###################################Creating storage commands Variables##########################') storage_file = open("Storage-output.txt", 'w') sys.stdout = storage...


how to redirect the output of python code to a file

How to write the output of python code to a file inside the same python script # Reading an excel file using Python import xlrd # Give the location of the file loc = ("C:\\Users\\212515181\\Desktop\\Dual_Mode_cfgctrl.xlsx") # To open Workbook wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) # Getting Root record value print("ROOT,"+ '"CONFIGMDL"') # Getti...


Redirect bash output to python script

I am using zbarimg to scan bar codes, I want to redirect the output to a python script. How can I redirect the output of the following command: zbarimg code.png to a python script, and what should be the script like? I tried the following script: #!/usr/local/bin/python s = raw_input() print s I made it an executable by issuing the...


input - How to redirect output in different files in python

I am using the python script that takes two input files (goodProteins.fasta and list.txt) and save result in gene.fasta output files. fasta_file = "goodProteins.fasta" # First input wanted_file = "list.txt" # Second input result_file = "result.txt" # Output fasta file wanted = set() with open(wanted_file) as f: for line in f: line = line.strip() if line != "": wanted.add(...


bash - Redirect the output of a python script to THE BEGINNING of a file

I am aware of the following options to append the output to a file: test.py: print "Error" print "Warning" test.txt: Levels: Debug When I do: python test.py > test.txt It appends at the end of the file. However, if I want to append at the beginning of a file, so that the output of my file looks like as f...


Redirect print output to file in Python

I am trying to redirect print output to a file in Python 3.4 - right now as it stands my script prints to the shell. I don't really need it to do that. Here's my code: with open('Input.txt') as namelist: for line in namelist: line_lower = line.lower() a = namelist.readline() if fuzz.ratio(a, line) >= 95: print(fuzz.ratio(a, line)) print(a + ": " + line)...


I can't redirect output of a python file from a php call

I'm trying to execute a python file from php, in python file I have this: import sys from subprocess import PIPE, Popen nom = sys.argv[1]; print nom def cmdline(command): process = Popen( args=command, stdout=PIPE, shell=True ) return process.communicate()[0] cmdline("nmap x.x.x.x -oX sortida.xml") When I execute python pythonfile.py works, creat...


redirect output file from one python script as input file in another python script

I wrote a python script for file manipulations, Since I don't know the way to redirect output file from one python script as input file in another python script, I have to run both the scripts separately. I want to learn as to how to pass on the output file from one script as input file for another script. Can someone please guide me regarding this query?


Redirect the output of python script into a text file

This question already has answers here:


linux - Output redirect for python

I have python code that looks like this: cmd = './job1' print(cmd) os.system(cmd) If I run this, the output looks like: ./job1 done. But if I run it with output re-direct, say: python mycode.py > out1.log then 'out1.log' looks like this: done. ./job1 basically, if I run the python code using output redirect...


Redirect output to two files in python

I am writing code where i want to redirect output two different files in python one for log purpose and another for fabric code creation. Below is the code which redirect output to two different files: import sys print('###################################Creating storage commands Variables##########################') storage_file = open("Storage-output.txt", 'w') sys.stdout = storage...


how to redirect the output of python code to a file

How to write the output of python code to a file inside the same python script # Reading an excel file using Python import xlrd # Give the location of the file loc = ("C:\\Users\\212515181\\Desktop\\Dual_Mode_cfgctrl.xlsx") # To open Workbook wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) # Getting Root record value print("ROOT,"+ '"CONFIGMDL"') # Getti...


bash - Redirect command to input of another in Python

I would like to replicate this in python: gvimdiff <(hg cat file.txt) file.txt (hg cat file.txt outputs the most recently committed version of file.txt) I know how to pipe the file to gvimdiff, but it won't accept another file: $ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" Getting to the python part... # hg...


Python + Django page redirect

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?


python - How to pass information using an HTTP redirect (in Django)

I have a view that accepts a form submission and updates a model. After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page. How can I "pass" this message to the other page? HttpResponseRedirect only accepts a URL. I've seen this done bef...


python - Django: Redirect to previous page after login

I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I ...


python - How to Redirect To Same Page on Failed Login

The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page. For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I wou...


cgi - How to redirect to another page in Python in CGIAr

If I want to redirect the user from a cgi script to a HTML page using core libraries from the following: import cgi Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python. If you have to physically write out the HTTP Response Headers to achieve this, then I would appreciate any i...


How to redirect stderr in Python? Via Python C API?

This is a combination of my two recent questions: [1] Python instance method in C [2] How to redirect stderr in Python? I would like to log the output of both stdout and stderr from a python script. The thing I want to ask is...


How to redirect stderr in Python?

I would like to log all the output of a Python script. I tried: import sys log = [] class writer(object): def write(self, data): log.append(data) sys.stdout = writer() sys.stderr = writer() Now, if I "print 'something' " it gets logged. But if I make for instance some syntax error, say "print 'something# ", it wont get logged - it will go into the console instead. Ho...


linux - Redirect stderr to stdout on exec-ed process from python?

In a bash script, I can write: exec 2>&1 exec someprog And the stderr output of someprog would be redirected to stdout. Is there any way to do a similar thing using python's os.exec* functions? This doesn't have to be portable, just work on Linux.


python - How to set cookies with redirect in Pylons

In light of the cookie-handling bugs affecting Safari and Chrome (see this thread), and Pylons implementation of redirect_to as an exception, is it possible to reliably set a tracking cookie and redirect at the same time? Is the META refresh method looked down upon?






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top