简体   繁体   中英

Process the output of python subprocess

I'm trying to make a system call in Python and store the output to a string so that I can process it in my Python program.To be more specific of what i am doing this a part of my code

r = subprocess.Popen(['c:\\Windows\\System32\\bash.exe', '-c', 'fuser somethingsomething'] , stdout=subprocess.PIPE )
output, errs = r.communicate()

How can i manipulate/save the output so that i can for example kill the process(if exists) fuser returns?I have tried to use decode('utf-8') but i haven't succeed so far.

EDIT

I replaced popen with check_output removed stdout=subprocess.PIPE and i got the output i wanted with output = r.decode('utf-8')

I had a similar question some weeks back, and finaly came up with this:

pids = []
with subprocess.Popen('tasklist | findstr /i "<your process name>"', shell=True, stdout=subprocess.PIPE, universal_newlines=True) as p:
    for line in p.stdout:
        pids.append([elem for elem in line.split() if elem != ''][1])

for pid in pids:
    subprocess.call('taskkill /f /pid ' + pid, shell=True)

Maybe it can be applied to your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM