How to call Linux commands in Python

Source: Internet
Author: User
Tags python script

First, using the OS module

In [1]:ImportOs#Import OS moduleIn [2]: Os.system ('ls') Anaconda-Ks.cfgepel-release-7-5. Noarch.rpmipython-4.1.2Ipython-4.1.2. Tar.gzpip-8.1.2Pip-8.1.2.tar.gz#md5=87083c0b9867963b29f7aba3613e8f4a.gzout[2]: 0In [3]: A=os.system ('ls')##得到的是执行的命令的返回值, not the result of executionAnaconda-Ks.cfgepel-release-7-5. Noarch.rpmipython-4.1.2Ipython-4.1.2. Tar.gzpip-8.1.2Pip-8.1.2.tar.gz#md5=87083c0b9867963b29f7aba3613e8f4a.gzIn [4]: A#executes the return value of the LS command, succeeds, 0out[4]: 0In [5]: B=os.popen ('ls'). ReadLines ()#assign the resulting results directly to the B listIn [6]: b#ls execution output to memory, then read all assigned to B listout[6]:['anaconda-ks.cfg\n', 'epel-release-7-5.noarch.rpm\n', 'ipython-4.1.2\n', 'ipython-4.1.2.tar.gz\n', 'pip-8.1.2\n', 'pip-8.1.2.tar.gz#md5=87083c0b9867963b29f7aba3613e8f4a.gz\n']

Common methods in >>>os modules (Linux commands)

Os.remove (): Delete file

Os.rename (): Rename file

Os.walk (): Generate all file names under the directory tree

Os.chdir (): Change Directory

Os.mkdir/makedirs: Creating a Directory/multi-level directory

Os.rmdir/removedirs: Delete directory/multi-level directory

Os.listdir (): Lists files for the specified directory

OS.GETCWD (): Get current working directory

Os.chmod (): Change directory Permissions

Os.path.basename (): Remove directory path, return file name

Os.path.dirname (): Remove file name, return directory path

Os.path.join (): Combines the parts of the separation into one path name

Os.path.getsize (): Return file size

Os.path.exists (): Presence

Os.path.isabs (): is an absolute path

Os.path.isdir (): Whether it is a directory

Os.path.isfile (): Whether it is a file

Second, using the commands module

In [7]:ImportCommands#Import Commands ModuleIn [8]: C=commands.getoutput ('ls')#ls command execution result, string form assignment to c variableIn [9]: cout[9]:'anaconda-ks.cfg\nepel-release-7-5.noarch.rpm\nipython-4.1.2\nipython-4.1.2.tar.gz\npip-8.1.2\ Npip-8.1.2.tar.gz#md5=87083c0b9867963b29f7aba3613e8f4a.gz'In [Ten]: D=c.split ('\ n')#for variable C, specify the delimiter \ n Delimited, the list is assigned to DIn [11]: dout[11]:['anaconda-ks.cfg', 'epel-release-7-5.noarch.rpm', 'ipython-4.1.2', 'ipython-4.1.2.tar.gz', 'pip-8.1.2', 'pip-8.1.2.tar.gz#md5=87083c0b9867963b29f7aba3613e8f4a.gz']

Three, read, ReadLine, ReadLines difference

1. Read () All out, put in a string

2. The ReadLine () method will read the contents of the memory space one line at a time and put it in a string

3. The ReadLines () method will take the contents of the memory space all at once and put it in a list.

Iv. Python scripting practices

1, write a Python script to implement the output of all users of Linux information, the format is as follows:

Username is the root uid is 0

Username is Xiaojin UID is 200

Username is bin UID is 10

Way One:

#!/usr/bin/pythonImportCommandsuser_str=commands.getoutput ('cat/etc/passwd') User_list=user_str.splitlines ()#List-delimited file contents (default by Row) forIinchUser_list:u_info=i.split (':')Print "username is", U_info[0],"UID is", U_info[2]

Way two:

#!/usr/bin/pythonImportOsuserlines=os.popen ("cat/etc/passwd"). ReadLines () forIinchUserlines:user_info=i.split (":")Print "username is", User_info[0],"\tuid is", User_infO[2]

2. Numerical script

1. Alert the user that the input content range is 0-100

2. Judge what the user entered, if not a number to give a reminder

3. Output user input

#!/usr/bin/pythonU_grade=raw_input ("Please input your grade:")ifU_grade.isdigit ():#IsDigit () method to convert a string to a percentageif0<=int (U_grade) <=100:Print "your grade is", U_gradeElse:Print "Please input the range of number 0-100"Else:Print "It ' s not a valid number,try again"

How to call Linux commands in Python

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.