(1) Os.system
Run system commands on only one child terminal and not get return information after command execution
Copy Code code as follows:
System (command)-> exit_status
Execute the command (a string) in a subshell.
If executed again under command line, the result is printed directly
Copy Code code as follows:
>>> os.system (' ls ')
04101419778.CHM Bash document Media py-django video
11.wmv Books Downloads Pictures python
all-20061022 Desktop Examples Project tools
(2) Os.popen
This method not only executes the command but also returns the information object after execution
Copy Code code as follows:
Popen (command [, mode= ' R ' [, BufSize]])-> pipe
Open a pipe to/from a command returning a file object.
For example:
Copy Code code as follows:
>>>tmp = Os.popen (' ls *.py '). ReadLines ()
>>>tmp
OUT[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 ']
The advantage is that the returned results are assigned to a variable that facilitates the processing of the program.
(3) using module subprocess
Copy Code code as follows:
>>> Import subprocess
>>> subprocess.call (["cmd", "Arg1", "Arg2"],shell=true)
Get Return and output:
Copy Code code as follows:
Import subprocess
p = subprocess. Popen (' ls ', shell=true, stdout=subprocess. PIPE, Stderr=subprocess. STDOUT)
For line in P.stdout.readlines ():
Print line,
retval = P.wait ()
(4) Using module commands
Copy Code code as follows:
>>> Import Commands
>>> dir (commands)
[' __all__ ', ' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' getoutput ', ' getstatus ', ' getstatusoutput ', ' mk2arg ', ' Mkarg ']
>>> commands.getoutput ("date")
' Wed June 19:39:57 CST 2009 '
>>>
>>> commands.getstatusoutput ("date")
(0, ' Wed June 19:40:41 CST 2009 ')
Note: When you execute a command parameter or return containing Chinese text, it is recommended that you use subprocess, and if you use Os.popen, you will receive the following error:
Copy Code code as follows:
Traceback (most recent call last):
File "./test1.py", line, Inmain ()
File "./test1.py", line, in main
Fax.sendfax ()
File "./mailfax/fax.py", line, in SendFax
Os.popen (CMD)
Unicodeencodeerror: ' ASCII ' codec can ' t encode characters in position 46-52:ordinal not inrange (128)