1

In one of the files I am seeing issue:

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

Code snippet:

def run_process(self, cmd):
        sh = self.is_win()
        child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=sh)
        output = child.communicate()[0].strip().split('\n')
        return output, child.returncode
Quentin Pradet
  • 4,691
  • 2
  • 29
  • 41
codehelp
  • 21
  • 2

1 Answers1

2

Since you called subprocess.Popen() without text=True, Popen.communicate() returns bytes as documented, and you can't split bytes with a string. You can reproduce your error with the follow snippet:

>>> b'multi\nline'.split('\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

One fix is to use split(b"\n"). But since you're splitting on end of lines, I guess your command returns text, so the better solution is to pass text=True to subprocess.Popen(). The output of cmd will be decoded straight away, which will help see any encoding errors where you're best equipped to handle them.

Also, consider using subprocess.run() when the port to Python 3 is over as it's easier to use than subprocess.Popen.

Quentin Pradet
  • 4,691
  • 2
  • 29
  • 41
  • Getting 'builtin_function_or_method' object has no attribute 'subprocess' on changing Popen to run or on adding text=True. – codehelp Dec 19 '19 at 11:43
  • Alternate 1:def run_process(self, cmd): sh = self.is_win() child = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=sh) output = child.communicate()[0].strip().split('\n') return output, child.returncode – codehelp Dec 20 '19 at 08:34
  • Alternate2: def run_process(self, cmd): sh = self.is_win() child = subprocess.Popen(cmd, text=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=sh) output = child.communicate()[0].strip().split('\n') return output, child.returncode – codehelp Dec 20 '19 at 08:35