Mr39
Mr39

Reputation: 61

Running tracert through python on windows just keeps going

i have the following script that runs tracert through a python script and it works kind of, like it will print out all the results fine. But then after the last hop it just keeps printing out blank lines, not sure what i am doing wrong here, if anyone can please help me out.

Below is the script that i have

from subprocess import Popen, PIPE
hostname = "1.1.1.154"
p = Popen("cmd /c tracert " + hostname, shell=True, stdout=PIPE)
for line in iter(p.stdout.readline, ""):
    print(str(line, 'utf-8'))

Upvotes: 0

Views: 146

Answers (1)

wjandrea
wjandrea

Reputation: 33107

iter will keep going until p.stdout.readline returns an empty string, but p.stdout.readline returns an empty bytes object.

However, you don't need to use iter(p.stdout.readline, b''). There's a better option: set the encoding when calling Popen, and iterate over p.stdout since it's a file-like object.

from subprocess import Popen, PIPE
hostname = "1.1.1.154"
p = Popen("cmd /c tracert " + hostname, shell=True, stdout=PIPE, encoding='utf-8')
for line in p.stdout:
    print(line.rstrip('\n'))

BTW use str.rstrip('\n') to remove trailing newlines.

Upvotes: 1

Related Questions