2
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

Jason
  • 393
  • 1
  • 4
  • 9
  • You likely want `.strip()` or `.rstrip()` (e.g. `file.write(line.rstrip())`). Note `line` is almost definitely already a string, so converting it is unnecessary. Also, you should look into the `with` keyword for opening files using context managers. – jedwards Jan 06 '17 at 03:13
  • 1
    Actually `subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)` will return `bytes`. Instead of `file.write(str(line))`, do `file.write(line.decode('ascii').strip())`. – Abdou Jan 06 '17 at 03:16
  • `Popen()` works with bytes so maybe you have to `encode/decode` data - or maybe you have to open file in bytes mode `b`. – furas Jan 06 '17 at 03:21

3 Answers3

3

The problem may not be so much about replacing or stripping extra characters as it is about what gets returned when you run subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE). The latter actually returns bytes, which may not play so nicely with writing each line to the file. You should be able to convert the bytes to string before writing the lines to the file with the following:

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(line.decode('ascii')) # to have each output in one line

file.close()

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:

cmd = 'tasklist'
proc = subprocess.getoutput(cmd)
file.write(proc)
file.close()

I hope this proves useful.

Abdou
  • 12,931
  • 4
  • 39
  • 42
1

You will indeed use strip() once again:

In [1]: 'foo\r\n'.strip()
Out[1]: 'foo'

In your case:

file.write(str(line).strip())

You can avoid having to close() your file by using with too:

with open("Process_list.txt", "r+") as file:
    for line in proc.stdout:
        file.write(str(line).strip())

Also, note that str() is only necessary of line is not already a string.

elethan
  • 16,408
  • 8
  • 64
  • 87
1

Perhaps you're looking for str.rstrip(). It removes trailing newline and carriage return characters; however, it also removes all trailing whitespace, so be aware of that.

Thelmund
  • 126
  • 1
  • 9