0

I'm trying to get the hostname where the .py is running, so I used:

server = subprocess.Popen(["hostname"])
print(server.stdout)

However, I'm getting this return:

None
HOSTNAME

It always prints a None from the subprocess.Popen() and then the hostname at print(server.stdout). Is there a way to fix this?

2
  • 1
    No, it's printing None from print(server.stdout) (because you didn't tell it to capture stdout), and the subprocess is sending HOSTNAME directly to your terminal. You need to add a stdout=subprocess.PIPE parameter to Popen(). Commented Dec 13, 2022 at 16:12
  • Now it's returning <Popen: returncode: None args: ['hostname']> Commented Dec 13, 2022 at 16:13

1 Answer 1

2

I've three solutions so far:

  1. Using Popen and stdout.read:
import subprocess
server = subprocess.Popen(["hostname"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(server.stdout.read().decode().rstrip("\n"))
  1. Using Popen and communicate
import subprocess
server = subprocess.Popen(["hostname"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = server.communicate()
print(out.decode().rstrip("\n"))
  1. Using check_output:
import subprocess
print(subprocess.check_output("hostname").decode().rstrip("\n"))

I'm wondering if you can get a string directly, but it works.

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

6 Comments

To remove the b' prefix and \n' suffix should I use .replace?
Hold, up, I'll change it for you.
The server runs python 3.6. Is there an alternative for removesuffix()?
Sure, use rstrip or strip since it's just one character.
No, I've updated the response. (You should use decode)
|

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.