Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of writing shell script by python

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces python to write shell script method, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Let's start with a function:

Os.system (command)

This function can call shell to run the command line command and return its return value. Try typing os.system ("ls-l") in the python interpreter and you can see that "ls" lists the files in the current directory. It can be said that through this function, python has all the capabilities of shell. Heh heh. However, usually this command does not need to be used. Because the commands commonly used in shell are usually written in python in a corresponding and equally concise way.

The most commonly used command in shell is the ls command. The corresponding word for python is: os.listdir (dirname). This function returns a list of strings containing all the file names, but not "." And "..". It's a little more complicated if you want to traverse the entire directory. Let's talk about it later. Try it in the interpreter first:

> > os.listdir ("/")

['tmp',' misc', 'opt',' root', '.autorelabel', 'sbin',' srv', '.autofsck', 'mnt',' usr', 'var',' etc', 'selinux',' lib', 'net',' lost found', 'sys',' media', 'dev',' proc', 'boot',' home', 'bin']

Just like this, all the following commands can be run directly in the python interpreter to see the results.

Corresponding to the cp command: shutil.copy (src,dest), this function takes two arguments, the parameter src refers to the name of the source file, and the parameter dest refers to the name of the target file or directory. If dest is a directory name, a file with the same name will be created in that directory. Similar to the shutil.copy function is shutil.copy2 (src,dest), but copy2 also copies the last access time and last update time.

However, the cp command of shell can also copy directories, but not shutil.copy of python, and the first parameter can only be a file. What are we going to do? Actually, python also has a shutil.copytree (src,dst [, symlinks]). The parameter has an extra symlinks, which is a Boolean value, and if it is True, create a symbolic link.

Move or rename files and directories? Probably guessed by smart friends, shutil.move (src,dst), hehe. Similar to the mv command, if src and dst are on the same file system, shutil.move simply changes the name. If src and dst are on different file systems, shutil.move will first copy src to dst, and then delete the src file. Seeing that most of my friends should have some idea of what python can do, I'll make a list of other functions:

Os.chdir (dirname)

Change the current working directory to dirname

Os.getcwd ()

Returns the current working directory path

Os.chroot (dirname)

Use dirname as the root of the process. Similar to the chroot command under * nix

Os.chmod (path,mode)

Change the permission bit of path. Mode can be a combination of the following values (using or):

Os.S_ISUID

Os.S_ISGID

Os.S_ENFMT

Os.S_ISVTX

Os.S_IREAD

Os.S_IWRITE

Os.S_IEXEC

Os.S_IRWXU

Os.S_IRUSR

Os.S_IWUSR

Os.S_IXUSR

Os.S_IRWXG

Os.S_IRGRP

Os.S_IWGRP

Os.S_IXGRP

Os.S_IRWXO

Os.S_IROTH

Os.S_IWOTH

Os.S_IXOTH

I won't go into details about what they mean. Basically, R stands for reading, W for writing, and X for executive authority. USR represents users, GRP represents groups, and OTH represents others.

Os.chown (path,uid,gid)

Change the owner of the document. The original owner is not changed when uid and gid are-1.

Os.link (src,dst)

Create a hard connection

Os.mkdir (path, [mode])

Create a directory. For the meaning of mode, see os.chmod (). The default is 0777.

Os.makedirs (path, [mode])

Similar to os.mkdir (), but first creates a parent directory that does not exist.

Os.readlink (path)

Returns the path that the symbolic link path points to

Os.remove (path)

Delete files, cannot be used to delete directories

Os.rmdir (path)

Delete a folder and cannot be used to delete files

Os.symlink (src,dst)

Create symbolic links

Shutil.rmtree (path [, ignore_errors [, onerror]])

Delete folder

Introduced so much, in fact, just look up the documents of os and shutil modules, hehe. When actually writing shell scripts, you also need to pay attention to:

1. Environment variable. The environment variable of python is saved in the os.environ dictionary, which can be modified in a normal dictionary, and will be inherited automatically when you start other programs using system. For example:

Os.environ ["fish"] = "nothing"

Note, however, that the value of an environment variable can only be a string. Unlike shell, python does not have the concept of export environment variables. Why not? Because there is no need for python to: -)

The 2.os.path module contains a lot of functions about pathname handling. Pathname processing does not seem to be very important in shell, but it is often needed in python. The two most commonly used are separating and merging directory and file names:

Os.path.split (path)-> (dirname,basename)

This function splits a path into two parts, for example: os.path.split ("/ foo / bar.dat") returns ("/ foo", "bar.dat")

Os.path.join (dirname,basename)

This function combines the directory name and file name into a complete pathname, for example: os.path.join ("/ foo", "bar.dat") returns "/ foo/bar.dat". This function is the opposite of os.path.split ().

And these functions:

Os.path.abspath (path)

Convert path to absolute path

Os.path.expanduser (path)

Convert "~" and "~ user" contained in path into user directories

Os.path.expandvars (path)

Replace "$name" and "${name}" contained in path according to the value of the environment variable, such as the environment variable FISH=nothing, then os.path.expandvars ("$FISH/abc") returns "nothing/abc"

Os.path.normpath (path)

Remove the "." contained in path. And ".."

Os.path.splitext (path)

Separate path into a base name and an extension. For example: os.path.splitext ("/ foo/ bar.tar.bz2") returns ('/ foo/bar.tar', '.bz2'). Note the difference between it and os.path.split ()

3. There is a useful function called os.stat () in the os module that is not introduced, because the os.path module contains a set of functions that have the same function, but the name is easier to remember.

Os.path.exists (path)

Determine whether a file or directory exists

Os.path.isfile ()

Determine whether path points to a normal file, not a directory

Os.path.isdir (path)

Determine whether path points to a directory rather than an ordinary file

Os.path.islink (path)

Determine whether path is pointing to a symbolic link

Os.path.ismount (path)

Determine whether the path is pointing to a mount point.

Os.path.getatime (path)

Returns the last access time of the file or directory pointed to by path.

Os.path.getmtime (path)

Returns the last modification time of the file or directory pointed to by path

Os.path.getctime (path)

Returns the creation time of the file pointed to by path

Os.path.getsize (path)

Returns the size of the file pointed to by path

4. Writing shell scripts with python often uses os,shutil,glob (file name of regular expression), tempfile (temporary file), pwd (operation / etc/passwd file), grp (operation / etc/group file), and commands (to get the output of a command). The first two have been basically introduced, the last few are very simple, just take a look at the documentation.

5.sys.argv is a list that holds the command-line arguments of the python program. Where sys.argv [0] is the name of the program itself.

Instead of talking without practice, let's write a simple script to copy files. The colleague who asked me to write the script the other day has a directory of tens of thousands of files. He wants to copy these files to other directories, but he can't copy the directory itself directly. He tried "cp src/* dest/" and reported an error that the command line was too long and asked me to write a script for him. Fuck python:

Import sys,os.path,shutil

For f in os.listdir (sys.argv [1]):

Shutil.copy (os.path.join (sys.argv [1], f), sys.argv [2])

Try the post in the linuxapp version again-rename all the files in a folder to 1000110999. You can write like this:

Import os.path,sysdirname=sys.argv [1] i=10001for f in os.listdir (dirname): src=os.path.join (dirname,f) if os.path.isdir (src): continueos.rename (src,str (I)) iTunes 1

Os.chkdir (path) is converted to the directory path.

Os.system ('md a') can create directories directly.

The os.name string indicates the platform you are using. For example, for Windows, it is' nt', 'and for Linux/Unix users, it is' posix'.

The ● os.getcwd () function gets the current working directory, which is the directory path where the current Python script works.

The ● os.getenv () and os.putenv () functions are used to read and set environment variables, respectively.

● os.listdir () returns all file and directory names under the specified directory.

The ● os.remove () function is used to delete a file.

The ● os.system () function is used to run the shell command.

The ● os.linesep string gives the line Terminator used by the current platform. For example, Windows uses'\ r\ n' while Mac uses'\ r'.

The ● os.path.split () function returns the directory name and file name of a path.

> > os.path.split ('/ home/swaroop/byte/code/poem.txt')

('/ home/swaroop/byte/code', 'poem.txt')

The ● os.path.isfile () and os.path.isdir () functions verify whether the given path is a file or a directory, respectively. Similarly, the os.path.exists () function is used to verify that the given path really exists.

File redirection

There is an existing PY file new1.py. Type: new1 > new.txt at the command line to output the results of the new1 run to the file new.txt, which is called stream redirection.

This is the end of the method of writing shell scripts for python. I hope the above content can be of some help and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report