4 ways to execute Python Linux system commands - forward

 

Contributors: junjie font: [increase decrease] Type: Reprinted time: 2014-10-21 I want to comment this article describes four methods to execute Python Linux system commands that call the Shell command in the Python script, needed friends can refer to
(1) os.system run in only one sub-terminal system commands, and returns information copy the code can not be acquired after the command code is as follows:
system (command) -> the the exit_status the execute command (String a) in the subshell a .
performs the command again if the result printed out directly copy the code follows the code:
>>> the os.system ( 'LS') 04101419778.CHM the bash-Py Document Media Pictures pythonall Django video11.wmv Books Downloads Examples Project Tools Desktop-20,061,022 (2) os.popen performs not only the process command also returns information object after the execution of the code copy the code follows:
popen (command [, MODE = 'R & lt' [, the bufsize of]]) -> a pipe to pipe the Open / command from a returning a file object example: copy the code following code:
>>> tmp = os.popen ( 'ls * .py') readlines () >>> tmpOut [21]:. [ 'dump_db_pickle.py', 'dump_db_pickle_recs.py', 'dump_db_shelve.py', 'initdata. py ',' __ init__.py ', ' make_db_pickle.py ',' make_db_pickle_recs.py ',' make_db_shelve.py ',' peopleinteract_query.py ',' reader.py ',' testargv.py ',' teststreams.py ' , 'update_db_pickle.py', 'writer.py' ]
advantages in that: the result returned to impart a variable, to facilitate processing program. (3) using the code modules subprocess copy the code follows:
>>> >>> subprocess.call Import subprocess ([ "cmd", "arg1", "arg2"], the shell = True)
Get Returns and output: copy the code follows the code :
Import subprocessp subprocess.Popen = ( 'LS', the shell = True, subprocess.PIPE = stdout, stderr = subprocess.STDOUT) for Line in p.stdout.
>>> import commands >>> dir (commands) [ '__ all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus',' getstatusoutput ',' mk2arg ',' mkarg '] >>> commands.getoutput ( "date ")' Wed Jun 10 19:39:57 CST 2009 '>>>>>> commands.getstatusoutput ( "date") (0,' Wed Jun 10 19:40 : 41 CST 2009 ') NOTE: when the parameters or return execution command includes the Chinese characters, it is recommended to use the subprocess, if used os.popen following error occurs: copy the code code is as follows:
Traceback (MOST Recent Last Call) : File "./test1.py", line 56 , inmain () File "./test1.py", line 45, in main fax.sendFax () File "./mailfax/Fax.py", line 13, in sendFax os.popen (cmd) UnicodeEncodeError: ' ascii' codec can not encode characters in position 46-52:ordinal not inrange(128)

Guess you like

Origin www.cnblogs.com/logol/p/11961575.html