1

I am reusing a code from python2 in python3.

value = subprocess.check_output("/usr/bin/python3 tc.py " + sys.argv[1], shell=True)
search = "TC specific commands"
read_file = open("input.py", "r")
write_file = open("output.py", "w")

for line in read_file:
   if search not in line:
      write_file.write(line)
   else:
      line = line + "\n" + value
      write_file.write(line)

My tc.py has code like print ('<Some_text>\n' + \ '<Some_text2>\n' + \ '<Some_text3>')

In python2 the above program used to write following lines in output.py <Some_text> <Some_text2> <Some_text3>

In python3, I got a syntax error TypeError: Can't convert 'bytes' object to str implicitly

So, I change my above script as: line = line + "\n" + value -> line = line + "\n" + str(value)

the output is coming like b'<Some_text>\n<Some_text2>\n<Some_text3>

How can I make output in python 3 same as I was getting earlier in python2?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Sudip
  • 523
  • 2
  • 7
  • 14
  • Running Python as a subprocess of Python introduces all kinds of complications; is there a reason you don't simply (refactor `tc.py` so that you can) `import tc` and call its function(s) natively? – tripleee Mar 16 '21 at 06:54
  • `str(value)` no, that gives you *the string represetnation of a bytes object*, it isn't what you want. You probably just want `value.decode()` (assuming you want utf8) – juanpa.arrivillaga Mar 16 '21 at 07:04
  • As a further aside, you really [want to avoid `shell=True`](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess) here; `subprocess.check_output(["/usr/bin/python3", "tc.py", sys.argv[1]])` actually removes a bug (you would need to add shell quoting around `sys.argv[1]` for it to work correctly when the file name you pass in contains shell metacharacters). – tripleee Mar 16 '21 at 07:17

2 Answers2

0

Your subprocess output is coming in as 8-bit strings instead of Unicode. You just need to convert it.

value = value.decode('utf-8') 
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

Your result is a bytes-string-object.

b'<Some_text>\n<Some_text2>\n<Some_text3>

To get a string-object, you have to decode it. If you decode it, you have to use the correct encoding (default is utf-8).

Here's an interesting post

wuarmin
  • 3,274
  • 3
  • 18
  • 31