How to edit string from STDOUT
<p>I have this code:</p>

<pre><code>netshcmd = subprocess.Popen('netsh wlan stop hostednetwork', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
output, errors = netshcmd.communicate()
if errors:
    print("Warrning: ", errors)
else:
    print("Success", output)
</code></pre>

<p>and output is this: </p>

<pre><code>Success b'The hosted network stopped. \r\n\r\n'
</code></pre>

<p>How to get output like this "Success The hosted network stopped."?</p>

<p>Reading from a sub-process gives you a <em>bytestring</em>. You could either decode this bytestring (you'll have to find a suitable encoding), or use the <code>universal_newlines</code> option and have Python automatically decode it for you:</p>

<pre><code>netshcmd = subprocess.Popen(
    'netsh wlan stop hostednetwork', 
    shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
    universal_newlines=True)
</code></pre>

<p>From the <a href="https://docs.python.org/3/library/subprocess.html#frequently-used-arguments" rel="nofollow"><em>Frequently Used Arguments</em> documentation section</a>:</p>

<blockquote>
  <p>If <em>universal_newlines</em> is <code>True</code>, these file objects will be opened as text streams in universal newlines mode using the encoding returned by <code>locale.getpreferredencoding(False)</code>. For <code>stdin</code>, line ending characters <code>'\n'</code> in the input will be converted to the default line separator <code>os.linesep</code>. For <code>stdout</code> and <code>stderr</code>, all line endings in the output will be converted to <code>'\n'</code>. For more information see the documentation of the <code>io.TextIOWrapper</code> class when the newline argument to its constructor is <code>None</code>.</p>
</blockquote>

<p>For a process run via the shell, <code>locale.getpreferredencoding(False)</code> should be <em>exactly</em> the right codec to use, as that gets the information on what encoding to use from the exact same location that other processes like <code>netsh</code> are supposed to consult, the <a href="https://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html" rel="nofollow">locale environment variables</a>.</p>

<p>With <code>universal_newlines=True</code>, <code>output</code> will be set to the string <code>'The hosted network stopped. \n\n'; note the newlines at the end. You may want to use</code>str.strip()` to remove the extra whitespace there:</p>

<pre><code>print("Success", output.strip())
</code></pre>

python subprocess netsh