[Python recipe] Python calls the shell command to obtain the return value and returned information, pythonshell
#-*-Coding: UTF-8-*-import osimport subprocessimport signalclass MockLogger (object): ''' simulate the log class. Facilitate unit testing. '''Def _ init _ (self): self.info = self. error = self. critical = self. debug def debug (self, msg): print "_ LOGGER __:" + msg class Shell (object): ''' to package the Shell script. Run () is a normal call and will wait for the shell command to return. Run_background () is an asynchronous call and will return immediately. If you do not wait for the shell command to complete the asynchronous call, you can use get_status () to query the status or use wait () to enter the blocking status, wait until the shell execution is complete. After you use kill () to forcibly stop the script during asynchronous calling, you still need to use wait () to wait for the script to exit. TODO does not verify that Shell commands contain ultra-large output results. '''Def _ init _ (self, cmd): self. cmd = cmd # cmd includes commands and parameters self. ret_code = None self. ret_info = None self. err_info = None # Replace it with the specific logger self. logger = MockLogger () def run_background (self): ''' the shell command is executed in non-blocking mode (the default Popen mode ). '''Self. logger. debug ("run % s" % self. cmd) # Popen will throw an OSError exception when the command to be executed does not exist, but after shell = True, # shell will handle the error that the command does not exist, so there is no OSError exception, therefore, you do not need to process self. _ process = subprocess. popen (self. cmd, shell = True, stdout = subprocess. PIPE, stderr = subprocess. PIPE) # non-blocking def run (self): ''' execute shell commands in blocking mode. '''Self. run_background () self. wait () def wait (self): ''' wait until shell execution is complete. '''Self. logger. debug ("waiting % s" % self. cmd) self. ret_info, self. err_info = self. _ process. communicate () # blocking # returncode: A negative value-N indicates that the child was # terminated by signal N self. ret_code = self. _ process. returncode self. logger. debug ("waiting % s done. return code is % d "% (self. cmd, self. ret_code) def get_status (self): ''' get the script RUNNING status (RUNNING | FINISHED) ''' retcode = self. _ process. poll () if retcode = None: status = "RUNNING" else: status = "FINISHED" self. logger. debug ("% s status is % s" % (self. cmd, status) return status # The subprocess of Python2.4 does not have send_signal, terminate, and kill # So here we need to copy one, 2.7 can directly use self. _ process kill () def send_signal (self, sig): self. logger. debug ("send signal % s to % s" % (sig, self. cmd) OS. kill (self. _ process. pid, sig) def terminate (self): self. send_signal (signal. SIGTERM) def kill (self): self. send_signal (signal. SIGKILL) if _ name _ = "_ main _": '''test code''' #1. test normal sa = Shell ('who ') sa. run () print "return code:", sa. ret_code print "return info:", sa. ret_info #2. test stderr sb = Shell ('ls/export/dir_should_not_exists ') sb. run () print "return code:", sb. ret_code print "return info:", sb. ret_info print "error info:", sb. err_info #3. test background SC = Shell ('sleep 2') SC. run_background () print 'warmly hello from parent process' print "return code:", SC. ret_code print "status:", SC. get_status () SC. wait () print "return code:", SC. ret_code print "return info:", SC. ret_info #4. test kill import time sd = Shell ('sleep 2') sd. run_background () time. sleep (1) sd. kill () sd. wait () # NOTE, still need to wait print sd. ret_code print sd. ret_info #5. test multiple command and uncompleted command output se = Shell ('pwd; sleep 1; pwd; pwd') se. run_background () time. sleep (1) se. kill () se. wait () # NOTE, still need to wait print se. ret_code print se. ret_info #6. test wrong command sf = Shell ('aaaaa') sf. run () print sf. ret_code print sf. ret_info print sf. err_info
What is Python and Lua?
Python
Python (pronunciation: ['pai θ (latency) n; (US) 'pai θ 0000n]) is an object-oriented, explanatory computer programming language, it is also a powerful and complete general-purpose language with more than a decade of development history, mature and stable. Python has the most abundant and powerful class libraries in the scripting language and is sufficient to support most daily applications.
This language is very simple and clear syntax, suitable for completing a variety of high-level tasks, almost all operating systems can run.
At present, technologies based on this language are rapidly developing, the number of users is rapidly expanding, and there are a lot of related resources.
Python Hello World Program
The following is a simple program that outputs Hello World on a standard output device. This program is usually the first program to start learning programming languages:
#! /Usr/bin/env python
Print "Hello, world! "
Or:
Import sys
Sys. stdout. write ("Hello, world \ n ")
Python history
The founder of Python is Guido van rosum. During the Christmas Day of 1989, in Amsterdam, Guido was determined to develop a new script interpreter as an inheritance of the ABC language in order to make Christmas boring. Python is selected as the program name because it is a fan of the Flying Circus of Monty Python.
ABC is a teaching language designed by Guido. In Guido's opinion, ABC is a very elegant and powerful language designed specifically for non-professional programmers. However, the ABC language is not successful. The reason is that Guido believes that it is not open. Guido is determined to avoid this error in Python (indeed, it works well with other languages such as C, C ++ and Java ). At the same time, he also wants to implement things that flash in ABC but have never been implemented.
In this way, Python was born in Guido. In fact, the first implementation is on a Mac machine. It can be said that Python was developed from ABC and was mainly influenced by Modula-3 (another pretty beautiful and powerful language designed for small groups. It also integrates the Unix shell and C habits.
Positioning of Python in programming languages
Many large-scale software development plans, such as Zope, Mnet, and BitTorrent. Google, are widely used.
It is generally considered that Python is an explanatory language, but this statement is incorrect. In fact, when Python is executed. the source code in the py file is compiled into the byte code (bytecode) of Python, and then the compiled byte code is executed by the Python Virtual Machine. The basic idea of this mechanism is consistent with that of Java and. NET. However, what is different between Python Virtual Machine and Java or. NET Virtual Machine is that Python Virtual Machine is a more advanced Virtual Machine. The level here is not generally advanced, not to say that Python's Virtual Machine is better than Java or. NET is more powerful than Java or. NET, Python's Virtual Machine is far from the real Machine. Alternatively, Python Virtual Machine is a Virtual Machine with a higher abstraction level.
C-based Python compiled bytecode files, usually in. pyc format.
Python features
Scalability can be said to be Python as a kind of... the remaining full text>