Execute terminal command over python
Question:
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?
Answers:
I’ve three solutions so far:
- Using Popen and stdout.read:
import subprocess
server = subprocess.Popen(["hostname"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(server.stdout.read().decode().rstrip("n"))
- 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"))
- 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.
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?
I’ve three solutions so far:
- Using Popen and stdout.read:
import subprocess
server = subprocess.Popen(["hostname"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(server.stdout.read().decode().rstrip("n"))
- 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"))
- 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.