Convert bytes to a string

后端 未结 19 2315
野性不改
野性不改 2020-11-21 04:45

I\'m using this code to get standard output from an external program:

>>> from subprocess import *
>>> command_stdout = Popen([\'ls\', \'-l         


        
相关标签:
19条回答
  • 2020-11-21 05:18

    For your specific case of "run a shell command and get its output as text instead of bytes", on Python 3.7, you should use subprocess.run and pass in text=True (as well as capture_output=True to capture the output)

    command_result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
    command_result.stdout  # is a `str` containing your program's stdout
    

    text used to be called universal_newlines, and was changed (well, aliased) in Python 3.7. If you want to support Python versions before 3.7, pass in universal_newlines=True instead of text=True

    0 讨论(0)
提交回复
热议问题