In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to use the functions of python standard libraries sys and OS". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Python standard library sys
The sys module includes a set of very practical services with many functional methods and variables to deal with Python runtime configuration and resources, so that it can interact with other system environments outside the previous program, such as the python interpreter.
List of common functions of the sys module (import sys):
The dir (sys) dir () method looks at the methods available in the module. Note: if you are in the editor, be sure to declare the coding method of the code in advance, otherwise the Chinese will be garbled. Sys.argv implements passing parameters sys.exit ([arg]) to the program from outside the program. Arg=0 obtains the current system code for normal exit sys.getdefaultencoding (). Generally, it defaults to asciisys.setdefaultencoding () to set the system default code. When you execute dir (sys), you will not see this method. If it is not passed in the interpreter, you can first execute reload (sys), and then execute setdefaultencoding ('utf8'). Set the system code to utf8sys.getfilesystemencoding () to get the file system coding method. Return 'return under mbcs',mac' under Windows to get the string collection of the specified module search path. You can put the written module under a certain path, and you can correctly find sys.platform to get the current system platform when you import in the program. The sys.stdinsys.stdoutsys.stderr stdin,stdout, and stderr variables contain the stream object corresponding to the standard I _ map O stream. If you need better control over the output, and print doesn't meet the requirements, they're what you need. You can also replace them, redirect output and input to other devices (device), or handle them in a non-standard way. Sys.modules is a global dictionary that is loaded in memory after python is started. Whenever a programmer imports a new module, sys.modules automatically records the module. When the module is imported the second time, python looks it up directly in the dictionary to speed up the program. It has all the methods that a dictionary has.
Python standard library os
The os module is responsible for the interaction between the program and the operating system, and provides an interface to access the underlying operating system.
List of common functions of the os module (import os):
Function-description:
Os.environ A dictionary contains a mapping of environment variables
Os.name displays the platform currently in use
Os.sep displays the path separator under the current platform
Os.linesep gives the line Terminator used by the current platform
Os.remove ('filename') deletes a file
Os.rename ("oldname", "newname") rename the file
Os.getcwd () displays the current python script work path
Os.chdir (dir) changes the current directory. Note that escaping is used under windows.
Os.listdir ('dirname') returns all file and directory names under the specified directory
Os.makedirs ('dirname/dirname') can generate a multi-layer recursive directory
Os.rmdir ('dirname') delete single-level directory
Os.getlogin () gets the user login name
Os.getenv ('key') gets the environment variable configuration
Os.putenv ('key') sets environment variables
Os.system () runs the shell command, note: here is to open a new shell, run the command, and when the command finishes, close shell.
Examples of operation:
Os.mkdir ('/ tmp/xx'), os.system ("echo'hello' > / tmp/xx/a.txt"), os.listdir ('/ tmp/xx') os.rename ('/ tmp/xx/a.txt','/tmp/xx/b.txt'), os.remove ('/ tmp/xx/b.txt'), os.rmdir ('/ tmp/xx')
Write a simple shell in python:
#! / usr/bin/pythonimport os, syscmd = sys.stdin.readline (); while cmd:os.system (cmd); cmd = sys.stdin.readline ()
Os.path
Function-description:
Os.path.abspath () gets the absolute path os.path.abspath ("1.txt") = = os.path.join (os.getcwd (), "1.txt")
Os.path.split () is used to separate the directory part from the file name part of a directory name.
Os.pardir represents the characters of the directory one level up under the current platform.
Os.path.join (path, name) connects to the directory and file name.
Os.path.basename (path) returns the file name
Os.path.dirname (path) returns the file path
Os.path.getctime ("/ root/1.txt") returns the ctime (creation time) timestamp of 1.txt
Os.path.exists (os.getcwd ()) determines whether the file exists
Os.path.isfile (os.getcwd ()) determines whether it is a file name, and whether 1 is 0 or not
Os.path.isdir ('c:\ Python\ temp') determines whether it is a directory, and whether 1 is 0 or not
Whether os.path.islink ('/ home/111.sql') is a symbolic link is not available under windows
Whether os.path.ismout (os.getcwd ()) is a file system mount point is not available under windows.
Os.path.samefile (os.getcwd (),'/ home') to see if the two file names refer to the same file.
Os.walk () can traverse all the directories and files under a given directory.
Os.path.walk ('/ home/huaying', test_fun, "a.c") traverses all subdirectories under / home/huaying, including this directory, and the function test_fun is called for each directory.
The difference between os.walk and os.path.walk
Function declaration: os.walk (top, topdown=True,None)
1. The parameter top indicates the path of the top-level directory to be traversed.
2. The default value of the parameter topdown is "True", which means that the files in the top-level directory are returned first, and then the files in the subdirectory are traversed. When the value of topdown is "False", it traverses the files in the subdirectory before returning the files in the top-level directory.
3. The default value of the parameter onerror is "None", which means that the error of traversing the file is ignored. If it is not empty, a custom function is provided to prompt the error message to continue traversing or throw an exception to abort the traversal.
Return value: the function returns a tuple containing three elements. These three elements are: the path name of each traversal, the list of subdirectories under the path, and the list of files under the directory.
Function declaration: os.path.walk (top, func, arg)
1. The parameter top indicates the directory path to be traversed.
2. The parameter func represents the callback function, that is, the function that handles the traversal path. The so-called callback function is used as a parameter of a function, and when triggered at a certain time, the program will call the defined callback function to handle a task. Note: the callback function of walk must provide three parameters: the first parameter is the parameter arg of os.path.walk, the second parameter represents the directory dirname, and the third parameter represents the file list names. Note: the list of files in the callback function of os.path.walk does not separate the subdirectory from the file as os.walk () does, but for a mixed discussion, you need to determine whether it is a file or a subdirectory in the callback function.
3. Parameter arg is the tuple passed to the callback function, which provides processing parameters for the callback function. Arg can be empty. The first parameter of the callback function is used to receive this incoming tuple.
Procedure: each directory in the top-rooted directory tree (including top itself, if it is a directory) calls the callback function funct with parameters (arg, dirname, names). The parameter dirname specifies the directory to access, and the parameter names lists the files in the directory (obtained from os.listdir (dirname)). The callback function can modify the names to change the settings of the directory accessed under the dirname, for example, to avoid accessing a part of the tree. (objects associated by names must be modified in place, assigned using del or slice.) Note: symbolic connections to directories are not treated as a subdirectory, and therefore walk () will not access them. The directories that access the connection must be identified by os.path.islink (file) and os.path.isdir (file), and walk () must be called.
Difference: the list of file names produced by os.path.walk () and os.walk () is not the same. Os.walk () produces the directory path and file path under the directory tree, while os.path.walk () produces only the file path (a mixed list of subdirectories and files).
Example:
# coding=utf-8importos# one-level directory characters on the current platform. Print (os.path.pardir) # os.path.abspath (_ _ file__): absolute path # get the absolute path (directory plus current file name) print (os.path.abspath (_ _ file__)) # os.path.split (os.getcwd ()) is used to separate the directory part and the file name part of a directory name. # get absolute directory (no file name) print (os.getcwd ()) Print (os.path.split (os.path.abspath (_ _ file__)) [0]) # directory print (os.path.dirname (os.path.abspath (_ _ file__) # is equivalent to the previous sentence # splicing file directory and file name print (os.path.join (os.path.abspath (_ _ file__)), os.path.pardir)) # get the parent directory # the path name of the current directory That is, the parent directory (os.path.dirname (): displays the current path, not the current file name) print (os.path.dirname (os.getcwd () Print (os.path.abspath (os.path.join (os.getcwd (), os.path.pardir)
This is the end of the introduction to "how to use the functions of the python standard libraries sys and OS". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.