Go to Python to execute system command methods

Source: Internet
Author: User

Portal

Python methods for executing system commands http://www.linux-field.com/?p=15

There are two common methods of executing system commands in Python:


Both require import OS

(1) Os.system

# Run System commands on only one sub-terminal and cannot get return information after command execution

System (command), Exit_status
Execute the command (a string) in a subshell.

# if the command line executes, the result is printed directly.

1 >>> os.system ('ls')2 04101419778.CHM   Bash      document    Media      py-Django   video3 each. wmv            Books     Downloads   Pictures  python4 all-20061022      Desktop   Examples    Project    Tools

(2) Os.popen

# This method not only executes the command but also returns the executed information object

Popen (command [, mode= ' R ' [, BufSize]]), pipe
Open a pipe to/from a command returning a file object.

For example:

1>>>tmp = Os.popen ('ls *.py'). ReadLines ()2>>>tmp3Out[21]:4['dump_db_pickle.py',5 'dump_db_pickle_recs.py',6 'dump_db_shelve.py',7 'initdata.py',8 '__init__.py',9 'make_db_pickle.py',Ten 'make_db_pickle_recs.py', One 'make_db_shelve.py', A 'peopleinteract_query.py', - 'reader.py', - 'testargv.py', the 'teststreams.py', - 'update_db_pickle.py', - 'writer.py']

The advantage is that the returned result is assigned to a variable to facilitate the processing of the program.

(3) using the module subprocess

1 Import subprocess 2 >>> subprocess.call (["cmd""arg1" "  arg2"],shell=true)

Get Return and output:

1 Import subprocess 2 p = subprocess. Popen ('ls', Shell=true, stdout=subprocess. PIPE, stderr=subprocess. STDOUT)3 for in p.stdout.readlines ():4     Print line ,5 retval = p.wait ()

(4) using module commands module

1>>>Importcommands2>>>dir (commands)3['__all__','__builtins__','__doc__','__file__','__name__','GetOutput','GetStatus','Getstatusoutput','Mk2arg','Mkarg']4>>> Commands.getoutput ("Date")5 'Wed June ten 19:39:57 CST'6>>>7>>> Commands.getstatusoutput ("Date")8(0,'Wed June ten 19:40:41 CST')

Note: subprocess is recommended when you execute a command's arguments or return with Chinese text, and the following error occurs if you use Os.popen:

1 Traceback (most recent):2File"./test1.py", line 56,inch<module>3 Main ()4File"./test1.py", line 45,inchMain5 Fax.sendfax ()6File"./mailfax/fax.py", Line 13,inchSendFax7 os.popen (cmd)8Unicodeencodeerror:'ASCII'Codec can'T encode characters in position 46-52:ordinal not InRange (+)

More extended reading addresses for this article:
http://zh-cn.how-to.mobi/index.php?id=89228

http://www.javaeye.com/topic/406623

Tags: Python, commands, subprocess, Popen

Go to Python to execute system command methods

Related Article

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.