Use Python to detect if a device is pinging through a

Source: Internet
Author: User
Tags stdin

Use python detects if a device Ping the pass

One, subprocess and the usual encapsulation functions
When we run Python, we are all creating and running a process. Like the Linux process, a process can fork a child process and let the child process exec another program. In Python, we fork a child process through the subprocess package in the standard library and run an external program.
The subprocess package defines a number of functions that create child processes, each of which creates child processes in different ways, so we can choose one to use as needed. In addition, Subprocess provides some tools for managing standard streams and pipelines (pipe) to use text communication between processes.

Subprocess.call ()
Parent process waits for child process to complete
Return exit information (ReturnCode, equivalent to Linux exit code)

Subprocess.check_call ()
Parent process waits for child process to complete
Returns 0
Check the exit information, and if ReturnCode is not 0, cite error subprocess. Calledprocesserror, this object contains the ReturnCode property, which can be try...except ... To check

Subprocess.check_output ()
Parent process waits for child process to complete
Returns the output of the child process to the standard output
Check the exit information, and if ReturnCode is not 0, cite error subprocess. Calledprocesserror, which contains the ReturnCode property and the output property, outputs a result of the standard output, available try...except ... To check.

These three functions are used in a similar way, as illustrated below with Subprocess.call ():

The code is as follows:


>>> Import subprocess
>>> retcode = Subprocess.call (["LS", "-l"])
#和shell中命令ls-a displays the same result
>>> Print Retcode
0


Place the program name (LS) with the parameter (-L) in a table and pass it to Subprocess.call ()

The shell defaults to False, under Linux, when Shell=false, Popen calls OS.EXECVP () to execute the program specified by args, shell=true, if Args is a string, Popen calls the system's shell directly to Line args Specifies the program, if args is a sequence, the first item of args is the definition program command string, and the other item is the additional parameter when invoking the system shell.

The above example can also be written as follows:

The code is as follows:

>>> retcode =subprocess.call ("Ls-l", Shell=true)


Under Windows, Popen calls CreateProcess () to execute the external program specified by args, regardless of the value of the shell. If args is a sequence, it is first converted to a string using List2cmdline (), but it is important to note that not all programs under MS Windows can be converted to command-line strings using List2cmdline.

Subprocess. Popen ()

The code is as follows:


Class Popen (args, bufsize=0, Executable=none, Stdin=none, Stdout=none,stderr=none, Preexec_fn=none, Close_fds=false, Shell=false, Cwd=none, Env=none,universal_newlines=false, Startupinfo=none, creationflags=0)


In fact, several of the above functions are based on the Popen () package (wrapper). The purpose of these packages is to make it easy for us to use child processes. When we want to personalize our needs more, we turn to the Popen class, which produces objects that represent child processes.

Unlike the package above, the main program does not automatically wait for the child process to complete after the Popen object is created. We must call the object's Wait () method, and the parent process waits (that is, block blocks), for example:

The code is as follows:

>>> Import subprocess
>>> child = subprocess. Popen ([' Ping ', '-C ', ' 4 ', ' www.baidu.com ')
>>> print ' parent process '


As seen from the results of the run, the parent process does not wait for the child to complete after it has been opened, but runs print directly.

Comparison of waiting conditions:

The code is as follows:

>>> Import subprocess
>>> child = subprocess. Popen (' Ping-c4 blog.linuxeye.com ', shell=true)
>>> child.wait ()
>>> print ' parent process '


As you can see from the results of the run, the parent process runs print after the child process is opened and waits for the children to complete.
In addition, you can also perform other operations on the child process in the parent process, such as in our example:

The code is as follows:


Child.poll () # Check child process status
Child.kill () # terminating child process
Child.send_signal () # Send a signal to a child process
Child.terminate () # terminating child process


The PID of the child process is stored in the Child.pid
Text flow control of sub-process
The standard input, standard output, and standard errors for child processes are represented by the following attributes:

The code is as follows:


Child.stdin
Child.stdout
Child.stderr


You can change standard input, standard output, and standard errors when Popen () is established, and can take advantage of subprocess. Pipes connect the inputs and outputs of multiple sub-processes together to form a pipe, as in the following 2 examples:

Copy the Code code as follows:

>>> Import subprocess
>>> child1 = subprocess. Popen (["LS", "-L"],stdout=subprocess. PIPE)
>>> print Child1.stdout.read (),
#或者child1. Communicate ()
>>> Import subprocess
>>> child1 =subprocess. Popen (["Cat", "/etc/passwd"],stdout=subprocess. PIPE)
>>> child2 = subprocess. Popen (["grep", "0:0"],stdin=child1.stdout,stdout=subprocess. PIPE)
>>> out = Child2.communicate ()


Subprocess. PIPE actually provides a buffer for text flow. The child1 stdout the text out to the buffer, and then Child2 's stdin reads the text from the pipe. The output text of the child2 is also stored in the pipe until the communicate () method reads the text from the pipe.
Note: Communicate () is a method of the Popen object that blocks the parent process until the child process finishes

third, see if a device Ping the Pass (source code)

1 Importsubprocess2 3  4 5 defTest ():6 7STR1 ='ping-c 3'8 9STR2 ='192.168.4.6'Ten  OneSTR3 ='| grep \ ' 0 received\ ' | wc-l' A  -Command = str1 + str2 +STR3 -  the     PrintCommand -  -p = subprocess. Popen (Command,shell=true, stdout=subprocess. PIPE) -  +result =P.stdout.read () -  +     PrintResult.strip () A  at   -  - if __name__=="__main__": -  -Test ()

Use Python to detect whether a device is ping-through

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.