0

I start programming with python on a Windows host. While simple examples work for unix like system I have to handle some Windows specifics like the line ending.

The following python script fails with an

TypeError: a bytes-like object is required, not 'str'

for the last line of the function run in this example:

import sys
import subprocess

def run(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdoutdata, stderrdata = p.communicate()
    if stderrdata:
        sys.stderr.write('\n')
        sys.stderr.write(stderrdata)
    return [real_line for real_line in stdoutdata.split('\n') if real_line]

def main():
    run("dir c:\\");
    sys.exit(0)

if __name__ == "__main__":
    main()

I guess that this is related to the fact that the stdoutdata contain line endings with \r\n. But replacing the split parameter with '\r\n' doesn't help.

How can I modify the script to run on a Windows host without changing the tools to start the external program?

harper
  • 13,345
  • 8
  • 56
  • 105

0 Answers0