Cannot redirect output when I run Python script on Windows using just script's name
Are you asking about this?
It's in the Python README. Perhaps this patch is what you're looking for.Windows: When executing Python scripts on the command line using file type
associations (i.e. starting "script.py" instead of "python script.py"),
redirects may not work unless you set a specific registry key. See
the Knowledge Base article STDIN/STDOUT Redirection May Not Work If Started from a File Association.
Redirect stdout to a file in Python?
If you want to do the redirection within the Python script, setting sys.stdout
to a file object does the trick:
# for python3
import sys
with open('file', 'w') as sys.stdout:
print('test')
A far more common method is to use shell redirection when executing (same on Windows and Linux):$ python3 foo.py > file
how to direct output into a txt file in python in windows
If it were me, I would use David Heffernan's method above to write your variable to the text file (because other methods require the user to use a command prompt).
import itertools
file = open('out.txt', 'w')
variations = itertools.product('abc', repeat=3)
for variations in variations:
variation_string = ""
for letter in variations:
variation_string += letter
file.write(variation_string)
file.close()
Python Script Called in Powershell Fails to Write to Stdout when Piped to File
The root cause is with the way python handles STDOUT. Python does some low level detection to get the encoding of the system and then uses a io.TextIOWrapper
with the encoding set to what it detects and that's what you get in sys.stdout
(stderr and stdin have the same).
Now, this detection returns UTF-8 when running in the shell because powershell works in UTF-8 and puts a layer of translation between the system and the running program but when piping to another program the communication is direct without the powershell translation, this direct communication uses the system's encoding which for windows is cp1252 (AKA Windows-1252).
system <(cp1252)> posh <(utf-8)> python # here stdout returns to the shell
system <(cp1252)> posh <(utf-8)> python <(cp1252)> pipe| or redirect> # here stdout moves directly to the next program
As for your issue, without looking at the rest of your program and the input file my best guess is some encoding mismatch, most likely in the reading of the input file, by default python 3+ will read files in utf-8, if this file is in some other encoding you get errors, best case scenario you get garbage text, worst you get an encoding exception.To solve it you need to know which encoding your input file was created with, which may get tricky and detection is usually slow, other solution would be to work with the files in bytes but this may not be possible depending on the processing done.
How to automatically direct print statements' outputs to a file in python?
I believe this is the closest you'll get:
import sys
sys.stdout = open('file', 'w')
print 'test' # prints test to file
If you'd like to write to multiple locations, you can use the following. Any object with a write method can be assigned to sys.stdout in python.import sys
class Logger(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f = open('file', 'w')
sys.stdout = Logger(f, sys.stdout)
print "Python Magic"
Related Topics
Most Efficient Way to Reverse a Numpy Array
Find the Date for the First Monday After a Given Date
Destructuring-Bind Dictionary Contents
Dump to JSON Adds Additional Double Quotes and Escaping of Quotes
Python Socket Receive - Incoming Packets Always Have a Different Size
Getting Data from Ctypes Array into Numpy
Why Does Python Use 'Magic Methods'
Is There a Numpy Builtin to Reject Outliers from a List
How to Plot Only a Table in Matplotlib
Round Up to Second Decimal Place in Python
Apt Command Line Interface-Like Yes/No Input
What Does Model.Train() Do in Pytorch
Python Argparse: Default Value or Specified Value
How to Exit from Python Without Traceback
How Do Threads Work in Python, and What Are Common Python-Threading Specific Pitfalls