Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Execute terminal command over python

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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().removesuffix("\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().removesuffix("\n"))
  1. Using check_output:
import subprocess
print(subprocess.check_output("hostname").decode().removesuffix("\n"))

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading