Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting decode error.
#7
Can test function.
# cm.py
import subprocess

def run_process(cmd_args):
    with subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
        out, err = p.communicate()
    return out
E:\div_code\new
λ ptpython -i cm.py
>>> res = run_process('ls')

# Return bytes
>>> res
b'001.png\n002.png\n003.png\n004.png\ncm.py\n'

# To string
>>> res.decode()
'001.png\n002.png\n003.png\n004.png\ncm.py\n'

# Write to file
>>> with open('output.txt', 'w') as f:
...     f.write(f'Process Output: \n{res.decode()}\n')
output.txt:
Output:
Process Output: 001.png 002.png 003.png 004.png cm.py
If return out, err then it will be a tuple.
>>> res
(b'001.png\n002.png\n003.png\n004.png\ncm.py\noutput.txt\n', b'')

>>> res[0]
b'001.png\n002.png\n003.png\n004.png\ncm.py\noutput.txt\n'

>>> res[0].decode()
'001.png\n002.png\n003.png\n004.png\ncm.py\noutput.txt\n'

# Or unpack back
>>> out, err = res

>>> out
b'001.png\n002.png\n003.png\n004.png\ncm.py\noutput.txt\n'
Reply


Messages In This Thread
Getting decode error. - by shankar - Sep-13-2018, 07:23 AM
RE: Getting decode error. - by buran - Sep-13-2018, 07:32 AM
RE: Getting decode error. - by shankar - Sep-13-2018, 07:47 AM
RE: Getting decode error. - by snippsat - Sep-13-2018, 09:28 AM
RE: Getting decode error. - by shankar - Sep-13-2018, 09:48 AM
RE: Getting decode error. - by volcano63 - Sep-13-2018, 10:12 AM
RE: Getting decode error. - by snippsat - Sep-13-2018, 12:20 PM
RE: Getting decode error. - by shankar - Sep-14-2018, 07:13 AM
RE: Getting decode error. - by tinman - Sep-20-2019, 10:05 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Decode string ? JohnnyCoffee 1 833 Jan-11-2023, 12:29 AM
Last Post: bowlofred
  UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 error from Mysql call AkaAndrew123 1 3,468 Apr-28-2021, 08:16 AM
Last Post: AkaAndrew123
  JSON Decode error when using API to create dataframe Rubstiano7 4 2,967 Jan-11-2021, 07:52 PM
Last Post: buran
  how to encode and decode same value absolut 2 2,370 Sep-08-2020, 09:46 AM
Last Post: TomToad
  python-resize-image unicode decode error Pedroski55 3 3,502 Apr-21-2020, 10:56 AM
Last Post: Pedroski55
  struct.decode() and '\0' deanhystad 1 3,240 Apr-09-2020, 04:13 PM
Last Post: TomToad
  charmap codec can't decode byte error with gzipped file in python bluethundr 2 3,737 Apr-30-2019, 12:26 PM
Last Post: bluethundr
  decode base64 with python give error thailq 3 3,903 Sep-24-2018, 12:39 AM
Last Post: thailq
  how to decode UTF-8 in python 3 oco 3 37,438 Jun-05-2018, 11:05 AM
Last Post: wavic
  Ask help for utf-8 decode/encode forfan 12 10,888 Feb-25-2017, 02:04 AM
Last Post: forfan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020