0

I am looking for a solution to extract port from netstat and use it as variable. Issue is that when I print it, value is 0 although when I use same command in bash it returns correct port.

device_port = os.system("netstat -atnp 2>/dev/null | awk '/adb/ {print $4}' | cut -d ':' -f 2")

returns value 5037

print(device_port)

returns value 0

Im not sure why is this happening.

Thanks

1 Answer 1

1

Your first command doesn't return 5037, it prints 5037. That's a difference.

Look at the documentation of os.system: https://docs.python.org/3/library/os.html#os.system

It states that it will forward the stdout of the command to the console, and return the exit code of the command.

That's exactly what happens, your code prints 5037 to the console and returns 0 to indicate that the command succeeded.


Fix:

Use subprocess instead of os.system. It's even recommended in the official documentation of os.system. That will allow you to capture the output and write it to a variable:

import subprocess

command = subprocess.run("netstat -atnp 2>/dev/null | awk '/adb/ {print $4}' | cut -d ':' -f 2",
    check=True,  # Raise an error if the command failed
    capture_output=True,  # Capture the output (can be accessed via the .stdout member)
    text=True,  # Capture output as text, not as bytes
    shell=True)  # Run in shell. Required, because you use pipes.
    
device_port = int(command.stdout)  # Get the output and convert it to an int
print(device_port)  # Print the parsed port number

Here's a working example: https://ideone.com/guXXLl

I replaced your bash command with id -u, as your bash script didn't print anything on ideome, and therefore the int() conversion failed.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Finomnis! It works as you udescribed. Also thanks for recommendation regarding subprocess. I will switch all cmds from os.system to subprocess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.