Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Python when automated operation and maintenance often used method     - Installation and deployment of MariaDB under CentOS (Database)

- Oracle 11g RAC manually playing GI PSU patch (11.2.0.4.8) (Database)

- Vi syntax highlighting settings (Linux)

- CRF ++ Linux use (Linux)

- HBase cluster installation and deployment (Server)

- Linux user login ban (Linux)

- To see the Linux device tree (Linux)

- Use regular expressions to check whether the input box to enter a URL (Programming)

- How to Upgrade Ubuntu GNOME 14.10 to GNOME 3.16 Desktop (Linux)

- Linux, MySQL / MariaDB Galera Cluster Setup Process (Database)

- Oracle GoldenGate tutorial Second, configure and use (Database)

- How to network to share files between Windows, MAC and Linux (Linux)

- Configuring Allatori code confusion when developing general Java applications in NetBeans (Programming)

- JavaScript object - Flexible and dangerous (Programming)

- Linux System Getting Started Tutorial: Five image processing software (Linux)

- Snort build a secure Linux server (Linux)

- Management and application Oracle external table (Database)

- To install Cinnamon desktop environment on your Ubuntu 14.04 / 12.04 (Linux)

- How to fix apt-get update can not add a new CD-ROM error (Linux)

- Oracle 12c In-Memory Study (Database)

 
         
  Python when automated operation and maintenance often used method
     
  Add Date : 2018-11-21      
         
       
         
  I have to get the current working directory is the current working directory path Python script: os.getcwd ()

Returns the name of all files and directories in the specified directory: os.listdir ()
Function is used to delete a file: os.remove ()
Delete multiple directories: osremovedirs (r "c: python") // a little dangerous, then it Skilled
Whether the path is given a test file: os.path.isfile () // often use
Whether the path is given a test directory: os.path.isdir () // often use
Determine whether it is an absolute path: os.path.isabs ()
Path test whether a given real: os.path.exists ()
Delete Files
os.remove ( "file")
Delete the directory:
os.rmdir ( "dir") // only delete empty directories
shutil.rmtree ( "dir") // empty directory with the contents of the directory can be deleted
Conversion directory:
os.chdir ( "path") // Replace path
Returns a directory path and file name: os.path.split ()
Example: import os
os.path.split ( '/ home / swaroop / byte / code / poem.txt')
The result is: ( '/ home / swaroop / byte / code', 'poem.txt') // is the path and file name are listed all the more clear
Separation extension: os.path.splitext ()
>>> Os.path.splitext ( '/ soft / dir1 / test1.txt')
( '/ Soft / dir1 / test1', '.txt')

Get path name: os.path.dirname ()
>>> Os.path.dirname ( '/ soft / dir1 / test1.txt')
'/ Soft / dir1'

Get the file name: os.path.basename ()
>>> Os.path.basename ( '/ soft / dir1 / test1.txt')
'Test1.txt'


Run shell command: os.system ()
Read and set the environment variable: os.getenv () and os.putenv ()
Given the current platform used line terminator: os.linesep windows using ' r n', linux make
 
Use ' n' and mountainlion using ' r'
Display platform you are using: os.name for windows, he is 'nt', and for linux / unix
 
He is 'posix'
Rename: os.rename (old, new)
Create a multi-set directory: os.makedirs (r "c: python test")
Create a single directory: os.mkdir ( "test")
Get the file attributes os.stat (file)
Modify file permissions and timestamps: os.chmod (file)
Terminate the current process: os.exit () //python2.4 available
Get File Size: os.path.getsize (filename)

#! / Usr / bin / python
import os
tardir = '/ soft / dir2'
soudir = '/ soft / dir1'


allfile = os.listdir (soudir)
for fn in allfile:
     fullpath = soudir + os.sep + fn
     command = "cp% s% s"% (fullpath, tardir)
     if os.system (command) == 0:
        print 'cp is ok'


example:
[Root @ localhost class2] # more v3.py

#! / Usr / bin / python

 

import os --- import system function

import time --- Import function of time

 

source = [ '/ home / swaroop / byte', '/ home / swaroop / bin'] --- path or file to be backed up

 

target_dir = '/ mnt / e / backup /' --- Backup Destinations

 

today = target_dir + time.strftime ( '% Y% m% d') --- a function of time taken today's date

 

now = time.strftime ( '% H% M% S') --- a function of time taken out of date now

 

comment = raw_input ( 'Enter a comment ->') --- a comment to the backup output

if len (comment) == 0:

    target = today + os.sep + now + '.zip' ---- os.sep gives the directory separator according to your operating system

else:

    target = today + os.sep + now + '_' + comment.replace ( '', '_') + '.zip'

 

if not os.path.exists (today): ---- judge directory exists

    os.mkdir (today) # make directory ---- call linux command

    print 'Successfully created directory', today

 

zip_command = "zip -qr '% s'% s"% (target, '' .join (source)) --- joi specify a null separator, backup

 

if os.system (zip_command) == 0: os.system run command function, use this function if the system runs the same command. That run command in a shell - If the command runs successfully, it returns 0, otherwise it returns an error number.

    print 'Successful backup to', target

else:

    print 'Backup FAILED'


 
File operations:
os.mknod ( "test.txt") create an empty file
fp = open ( "test.txt", w) directly open a file, if the file does not exist, create a file
On open / file pattern:
w to open it for writing
a model with additional open (EOF from the start, creating a new file if necessary)
r + Open in read-write mode
w + // open in read-write mode is said to good use
a + // open in read-write mode I prefer to use, after opening additional literacy
rb opened in binary read mode
wb opened in binary write mode
opened in binary mode append ab
rb + Open binary read-write mode
wb + opened in binary read-write mode
ab + Open binary read-write mode
 
fp.read ([size]) // size of the read length in byte units
fp.readline ([size]) // read a line, if you define the size, it is possible to return only one row
 
section
fp.write (str) // the str written to a file, write () does not add a newline after str
fp.writelines (seq) // all contents seq written to a file (multi-line write-once). This one
 
Function only faithfully written, does not add anything at the end of each row
fp.close ()
fp.flush () // The contents of the buffer is written to disk
fp.fileno () // returns a long integer "File Label"
fp.isatty () // whether the file is a terminal device file (unix systems)
fp.tell () // returns the current position, such as:
fp = open ( "zhige.txt", 'a +') //zhige.txt the contents of zhigedahaoren
fp.read (3)
c = fp.tell ()
print c // returns show zhigedahaoren in the third letter i
fp.next () // returns the next line and the flag file operations move to the next line
When a file to be used for ... in file such a statement is to call the next () function to achieve traverse
 
of
fp.seek (offset [, whence]) // move the cursor to the file speak and tell offset position with
 
Experiment to see more obvious
fp.truncate ([size]) // cut the file size specified, the default is to cut the current file operations
 
For position coordinates. If the size is larger than file size, depending on the system, it may not change the text
 
Member, may also be used to fill 0 file the appropriate size, it might be a bunch of random stuff to add.
 
 
Directory operations: // feeling can os.system ( '') write shell completed
os.mkdir ( "file") to create the directory
Copy the file:
shutil.copyfile ( "oldfile", "newfile") // oldfile and newfile are intelligent file
shutil.copy ( "oldfile", "newfile") // oldfile only file, newfile can
 
So the file can also be a target directory
Copy the folder:
shutil.copytree ( "olddir", "newdir") // olddir and newdir can only be a directory,
 
And must not exist newdir
Rename the file (directory):
os.rename ( "oldname", "newname") // this is the file or directory command
Move the file (directory)
shutil.move ( "oldpos", "newpos")
 
 
Some explain:
 
seek (offset, where): where = 0 from the starting position, to move from the current position 1, 2
 
Moved from the end position. When line feed, line feed will be truncated. seek () returns no value, it is None.
tell (): The current location of the file that is to tell the location of the file pointer obtained by
 
seek, readline, read, readlines impact, the impact is not truncate
 
truncate (n): cut off from the start line of the first character of the file, the file is truncated to n characters; no n
 
It indicates truncation from the current position; after stage n later said to have been deleted words. Wherein the wrap win next generation of
 
Table 2 character size.
readline (n): number of lines read, n represents the maximum number of bytes read. Where to start reading
 
Location is tell () + 1. When n is empty, the default read the contents of the current row
 
readlines reads all lines
 
read reads all lines
 
 
Second, the role of the following in order to illustrate an example of the above functions
 
fso = open ( "f: a.txt", 'w +') // w + way to, not a way to open the file, so the file
 
Original content is cleared
print fso.tell () // original file contents are emptied, so at this time tell () = 0
 
fso.write ( "abcde n") // write the file abcde n, because the newline n accounted for two characters, it is written 7
 
Characters
print fso.tell () at this time tell () = 7
 
fso.write ( "fghwm") // and write to the file fghwm, so at this time co-written document 7 + 5 = 12 characters
print fso.tell () // this time tell () = 12
 
fso.seek (1,0) // from the first line of the file that is in fact the position of the first character to start moving a character
print fso.tell () // this time tell () = 1
 
print fso.readline () // read the current line, the first line of the file, but it will be from the second character
 
Began to read, the result is bcde
 
// Read the entire file if replaced for read or read the entire document, the result is bcdefghwm
print fso.tell () // this time because readline tell () = 7
 
fso.truncate (8) // from the top row of characters written to the file after the count, the truncated to eight characters, that is,
 
abced nf, ie the file contents: abcde nf
 
print fso.tell () // tell () still is 7, and is affected by truncate (8), but this time the file
 
The contents of abcde nf
 
print fso.readline () // () + 1 = 8 start reading, reading from the tell current line: f
     
         
       
         
  More:      
 
- Dom4j change XML coding (Programming)
- Ubuntu install VMware Workstation 11 tutorials at 14.04 / 14.10 (Linux)
- Linux common network tools: Scan routing of mtr (Linux)
- ORA-27054 NFS problem solving (Database)
- To remove those IP is prohibited Fail2ban on CentOS 6/7 (Server)
- Java developers question (Programming)
- Redhat Close SELinux correct step (Linux)
- Java Timer (regular calling, to achieve a fixed time to perform) (Programming)
- SQLite (Database)
- How to identify memory leaks in Java (Programming)
- Static member variable modified (Programming)
- OpenJDK7 source compiler installation on CentOS 6.5 (Linux)
- Hadoop new and old version of the difference in the size of the InputSplit (Server)
- Use Bosh deploy CloudFoundry problems encountered on OpenStack (Server)
- How to install Go1.5 source development environment on Mac (Server)
- Offline (local) Yum source structures (Linux)
- Interesting example of Linux Sort command (Linux)
- shell script: MySQL monitoring service is normal (Database)
- To generate a certificate using OpenSSL under Linux (Server)
- How to disable IPv6 on Ubuntu, Linux Mint, Debian (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.