import subprocess
cmd = 'tasklist'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
file = open("Process_list.txt", "r+")
for line in proc.stdout:
file.write(str(line))
file.close()
i just wrote saving process list to text file. But Process_list.txt file has lots of line feed character like \r\n. How can i remove it? i used replace and strip func before
The problem may not be so much about
replac
ing orstrip
ping extra characters as it is about what gets returned when you runsubprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
. The latter actually returnsbytes
, which may not play so nicely with writing each line to the file. You should be able to convert thebytes
tostring
before writing the lines to the file with the following:If you don't want to have each output in one line, then you can strip the newline characters with
file.write(line.decode('ascii').strip())
.Moreover, you could have actually used
subprocess.getoutput
to get an output of string characters and save the outputs to your file:I hope this proves useful.