Output ascii characters to stdout in Python 3
<p>I have a file named 'xxx.py' like this:</p>

<pre><code>print("a simple string")
</code></pre>

<p>and when I run that like this (Python 3):</p>

<pre><code>python xxx.py &gt;atextfile.txt
</code></pre>

<p>I get a unicode file.</p>

<p>I would like an ascii file.</p>

<p>I don't mind if an exception is thrown if a non-ascii character is attempted to be printed.</p>

<p>What is a simple change I can make to my code that will output ascii characters?</p>

<p>My searches turn up solutions that all seem too verbose for such a simple problem.</p>

<p>[Edit] to report what I learned from setting LC_CTYPE:</p>

<p>I am running on windows 7.</p>

<ol>
<li>When running on the powershell commandline I get a unicode file (two bytes/character)</li>
<li>When running in a .bat file without LC_CTYPE set I get an ascii file (could be utf-8 as @jwodder pointed out).</li>
<li>When running in a .bat file with LC_CTYPE=ascii set I get presumable an ascii file (1 byte/character).</li>
</ol>

<p>The <code>stdout</code> encoding is defined by the environment that is executing the python script, e.g.:</p>

<pre><code>$ python -c "import sys; print(sys.stdout.encoding)"
UTF-8
$ LC_CTYPE=ascii python -c "import sys; print(sys.stdout.encoding)"
US-ASCII
</code></pre>

<p>Try adjusting your environment before running the script. You can force the encoding value for Python by setting the <a href="https://docs.python.org/3.5/using/cmdline.html#envvar-PYTHONIOENCODING" rel="nofollow"><code>PYTHONIOENCODING</code></a> environment variable.</p>

python windows python-3.x unicode character-encoding