This question already has answers here:
Suppressing output in python subprocess call [duplicate]
(2 answers)
Get output of system ping without printing to the console
(2 answers)
Closed 5 years ago.
import subprocess, platform
def ping(host):
args = "ping -n 1 " + host
return subprocess.call(args) == 0
print(ping("www.google.com"))
I am using this code in order to ping a website to test whether it is up or down, which works perfectly, however it results in a command prompt window briefly appearing which is not ideal for what I am working on, so my question is;
How can I supress this window from appearing on pings requests (windows based solution needed)
To use ping to know whether an address is responding, use its return value, which is 0 for success. subprocess.check_call will raise and error if the return value is not 0. To suppress output, redirect stdout and stderr. With Python 3 you can use subprocess.DEVNULL rather than opening the null file in a block.
import os
import subprocess
with open(os.devnull, 'w') as DEVNULL:
try:
subprocess.check_call(
['ping', '-c', '3', '10.10.0.100'],
stdout=DEVNULL, # suppress output
stderr=DEVNULL
)
is_up = True
except subprocess.CalledProcessError:
is_up = False
Ref:Get output of system ping without printing to the console
Related
This question already has answers here:
How to hide output of subprocess
(5 answers)
Closed 2 years ago.
I am currently writing a python program that contains a section where it pings a target computer to see and it if responds, changes a variable, but when I execute the code the ping command writes to the console (which I don't want).
I have checked the ping commands parameters to see if there is something to make it silent but was unable to find anything. Is there something I can do to stop the command to echoing to the console?
My code below:
if platform.system().lower() == "windows":
parameter = "-n"
else:
parameter = "-c"
exitCode = subprocess.call(f"ping {parameter} 1 {activeConnections[ip][0]}")
if (exitCode == 0):
activeConnections[ip][3] = "T"
activeConnections is a dictionary and if the ping is successful, a value is changed from "F" to "T".
You can use the devnull attribute of the built-in os module:
from os import devnull
from subprocess import STDOUT
# Your code
if platform.system().lower() == "windows":
parameter = "-n"
else:
parameter = "-c"
with open(devnull) as DEVNULL:
exitCode = subprocess.call(f"ping {parameter} 1 {activeConnections[ip][0]}", stdout=DEVNULL, stderr=STDOUT))
if (exitCode == 0):
activeConnections[ip][3] = "T"
This question already has answers here:
Redirect subprocess stderr to stdout
(2 answers)
Closed 2 years ago.
I want to repeat block of codes until successful output but want to display only successful messages.
while i < 6:
try:
sys.tracebacklimit = 0 #this line seems not work
gluster_volume_names = []
gstatus_output = subprocess.check_output('gstatus -a -o json ', shell=True).decode()
date, time, json_part = gstatus_output.split(maxsplit=2)
gluster_info = json.loads(json_part)
volume_list = gluster_info["volume_summary"]
....
....
break
except:
i += 1
continue
But I don't know how to suppress these output below. (unsuccessful run) They are not the outcome I want. The block of code eventually ran successfully after less than 5 tries then exit.
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/gstatus-0.66-py3.6.egg/EGG-INFO/scripts/gstatus", line 143, in main
File "/usr/local/lib/python3.6/site-packages/gstatus-0.66-py3.6.egg/gstatus/libgluster/cluster.py", line 543, in update_state
gstatus.libutils.excepts.GlusterFailedVolume: Unable to query volume 'BLAH'
Possible cause: cluster is currently reconverging after a nodehas entered a disconnected state.
Response: Rerun gstatus or issue a peer status command to confirm
Please help!
Instead of using subprocess.check_output, you should use the standard subprocess.run method and pipe the standard error to /dev/null. Use the following instead:
gstatus_output = subprocess.run('gstatus -a -o json ', shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode()
If you just want to suppress the errors in the console on a linux-system you can try:
python yourCode.py 2>/dev/null
With this you can also suppress stdout:
python yourCode.py 1>/dev/null
One possibility is to redirect standard output and standard error to a string. After execution, you can choose whether to print the results of the string, or discard it and try again.
from contextlib import redirect_stdout, redirect_stderr
import io
f = io.StringIO()
with redirect_stdout(f):
with redirect_stderr(f):
.... whatever you want ....
s = f.getvalue()
This question already has answers here:
subprocess wildcard usage
(3 answers)
Closed 3 years ago.
import os
from subprocess import PIPE,Popen
#os.chdir("..")
cmd=["ls","*.py"]
try:
p=Popen(cmd,stdout=PIPE,universal_newlines=True,shell=True)
except Exception as e:
print(f"Exception:\t{e}")
for line in p.stdout:
print(line,end=" ")
p.stdout.close()
return_code=p.wait()
I am trying to get ls all python files in my server, however whenever I am writing the output which should be all .py files only, I am getting every file there, what am I doing wrong.
I tried ls *.py in server terminal and it works fine,however in script not working
You can directly use "ls *.py" as a command
import os
from subprocess import PIPE,Popen
#os.chdir("..")
cmd=["ls *.py"]
try:
p=Popen(cmd,stdout=PIPE,universal_newlines=True,shell=True)
except Exception as e:
print(f"Exception:\t{e}")
for line in p.stdout:
print(line,end=" ")
p.stdout.close()
return_code=p.wait()
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
This is my code so far:
import subprocess
def __init__(pingcount, hostname):
try:
out, error = subprocess.Popen.communicate(subprocess.Popen("ping -n " + pingcount + ' ' + hostname), timeout=10)
except subprocess.TimeoutExpired:
subprocess.Popen.kill(subprocess.Popen)
return "No connection to terminal. Contact system administrator."
print(str(out))
if str(out).find("rtt") != -1:
return str(out)[str(out).find("rtt"):]
else:
return "No connection to server."
Similar code works on Windows, but upon calling this function, I get a return value of None.
From PING(8) man page in Linux:
-c count Stop after sending count ECHO_REQUEST packets. With deadline option, ping waits for count ECHO_REPLY packets, until the timeout expires.
-n Numeric output only. No attempt will be made to lookup symbolic names for host addresses.
You're passing -n argument as a result the command fails in Linux:
$ ping -n 10 www.google.com
connect: Invalid argument
from subprocess import Popen, PIPE, TimeoutExpired
import sys
# inside class body
def __init__(pingcount, hostname):
if sys.platform == "linux":
cmd = ["ping", "-c", pingcount, hostname]
else:
cmd = "ping -n " + pingcount + ' ' + hostname # else: assume Windows
proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
try:
proc_stdout, proc_stderr = proc.communicate(timeout=19)
except TimeoutExpired:
proc.kill() # on Linux send SIGKILL signal
return "No connection to terminal. Contact system administrator."
# rest of code...
The if statement at the beginning simply checks the operating system on which Python is running to determined the right command to pass to Popen.
Note: using proc.kill send SIGTERM on POSIX operating systems like Linux. This is a very brutal way to kill the process. The operating system will forcibly terminate the process and remove it from memory. Probably you need to use proce.terminate instead. However, I don't see serious implications here for using proc.kill with ping. see Popen.kill section in the documentation of the subprocess module.
This question already has answers here:
subprocess.check_output return code
(5 answers)
Closed 7 years ago.
While developing python wrapper library for Android Debug Bridge (ADB), I'm using subprocess to execute adb commands in shell. Here is the simplified example:
import subprocess
...
def exec_adb_command(adb_command):
return = subprocess.call(adb_command)
If command executed propery exec_adb_command returns 0 which is OK.
But some adb commands return not only "0" or "1" but also generate some output which I want to catch also. adb devices for example:
D:\git\adb-lib\test>adb devices
List of devices attached
07eeb4bb device
I've already tried subprocess.check_output() for that purpose, and it does return output but not the return code ("0" or "1").
Ideally I would want to get a tuple where t[0] is return code and t[1] is actual output.
Am I missing something in subprocess module which already allows to get such kind of results?
Thanks!
Popen and communicate will allow you to get the output and the return code.
from subprocess import Popen,PIPE,STDOUT
out = Popen(["adb", "devices"],stderr=STDOUT,stdout=PIPE)
t = out.communicate()[0],out.returncode
print(t)
('List of devices attached \n\n', 0)
check_output may also be suitable, a non-zero exit status will raise a CalledProcessError:
from subprocess import check_output, CalledProcessError
try:
out = check_output(["adb", "devices"])
t = 0, out
except CalledProcessError as e:
t = e.returncode, e.message
You also need to redirect stderr to store the error output:
from subprocess import check_output, CalledProcessError
from tempfile import TemporaryFile
def get_out(*args):
with TemporaryFile() as t:
try:
out = check_output(args, stderr=t)
return 0, out
except CalledProcessError as e:
t.seek(0)
return e.returncode, t.read()
Just pass your commands:
In [5]: get_out("adb","devices")
Out[5]: (0, 'List of devices attached \n\n')
In [6]: get_out("adb","devices","foo")
Out[6]: (1, 'Usage: adb devices [-l]\n')