In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to use Python to expand and extend Nautilus, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
Nautilus script
The first way to extend Nautilus is through a specific directory named. Gnome2/nautilus-scripts found in / home. When you right-click a file or folder under the Scripts menu, all executable files in that directory will appear. You can also select multiple files or folders and pass the list of files to the script using the same right-click method.
When a script is called, Nautilus supports multiple environment variables that contain the current directory, selected files, and so on. Table 1 shows these environment variables.
Table 1. Nautilus environment variables
The environment variable describes the new line split path of the file selected by NAUTILUS_SCRIPT_SELECTED_FILE_PATHS (local only) the new line split of the file selected by NAUTILUS_SCRIPT_SELECTED_URIS the location and size of the current window of URIsNAUTILUS_SCRIPT_CURRENT_URI current location NAUTILUS_SCRIPT_WINDOW_GEOMETRY
In Python, you get the values of these variables through a call to the os.environ.get function, as follows:
Selected = os.environ.get ('NAUTILUS_SCRIPT_SELECTED_FILE_PATHS,'')
This call returns a string containing the arrival of all selected files separated by newline characters. Python simplifies returning this string to an iterable list with the following code:
Targets = selected.splitlines ()
At this point, maybe you should stop and talk about user interaction. When control is transferred from the Nautilus to the script, there is really no restriction on the script at this point. Depending on the role of the script, you don't even need any user feedback, except for some types of completion or error messages, which can be handled through some simple message boxes. Since the gtk windowing toolkit is used when writing Nautilus, although this is not necessary, it is logical to adopt the same approach. You can easily use TkInter or wxPython.
For the purposes of this article, you will adopt gtk. It takes only a few lines of code to generate a simple message box for the communication completion status, which is most appropriate if you want to create a simple function to generate the message for ease of reading. A total of 4 lines of code are required:
Def alert (msg): dialog = gtk.MessageDialog () dialog.set_markup (msg) dialog.run ()
Example: create a simple script to return the number of selected files
The first sample program combines multiple segments into a simple script to return the number of files currently selected. This script can be used for files or directories. You can use another Python library function, os.walk, to recursively build a list of files in each directory. There are 38 lines of code, as shown in listing 1, which is all the gadget needs, including blank lines.
Listing 1. Code Python for Filecount scripts
#! / usr/bin/env pythonimport pygtkpygtk.require ('2.0') import gtkimport osdef alert (msg): "Show a dialog with a simple message."dialog = gtk.MessageDialog () dialog.set_markup (msg) dialog.run () def main (): selected = os.environ.get (' NAUTILUS_SCRIPT_SELECTED_URIS','') curdir = os.environ.get ('NAUTILUS_SCRIPT_CURRENT_URI'') Os.curdir) if selected:targets = selected.splitlines () else:targets = [curdir] files = [] directories = [] for target in targets:if target.startswith ('file:///'):target = target [7:] for dirname, dirnames, filenames in os.walk (target): for dirname in dirnames:directories.append (dirname) for filename in filenames:files.append (filename) alert ('% s directories and% s files'% (len (directories)) Len (files)) if _ _ name__ = = "_ _ main__": main ()
Figure 1 shows what you see when you right-click a file or select a set of files. The Scripts menu option shows all executables in the. gnome2/nautilus-scripts and gives the option to open the folder. Select a file to execute the script.
Figure 1. Select a file in Nautilus
Figure 2 shows the running result of the Filecount.py script.
Figure 2. Filecount.py output
There are a few things to keep in mind when debugging Nautilus scripts. The first thing to do is to close all instances of Nautilus to reload it completely and find a new script or extension. You can use the following command:
Nautilus-Q
The next common command enables you to run Nautilus directly without having to open the preference or configuration data. This saves a lot of steps in solving problems such as inadvertent damage caused by scripts or extensions. The command is as follows:
Nautilus-no-desktop
The last step left to ensure that the filecount tool is accessible by Nautilus is to copy it to the ~ / .gnome2/nautilus-scripts directory and change the file code to allow execution, the related command is:
Chmod + x Filecount.py
Example: create File cleanup tool
The second example is the create file cleanup tool to find any files that might be temporarily generated by editors such as Vim or EMACS. By simply modifying the check function, you can use the same concept to clear the directory of any particular file. This code is a silent operation, which means that it does not provide any feedback to the user after execution.
The main function of the script looks basically the same as the example of the previous mask, except for a few trivial exceptions. This code invokes the main function several times using the concept of recursion until the last directory is processed. You can use the os.walk function instead of using recursion to accomplish the same task. File checking occurs in the check function, simply checking files that end with a tilde (~) or pound sign (#), and files that begin after a pound sign or end with the extension .pyc. This example shows the large number of functions provided by the os module of the Python standard library. It also provides examples of manipulating pathnames and directories independently of the operating system, as well as performing file operations. Listing 2 shows the code for the script.
Listing 2. Python code for cleanup scripts
#! / usr/bin/env pythonimport pygtkpygtk.require ('2.0') import gtkimport osdef check (path): "Returns true to indicate a file should be removed."if path.endswith (' ~'): return Trueif path.startswith ('#') and basename.endswith ('#'): return Trueif path.endswith ('.pyc'): return Truereturn Falsedef walk (dirname=None): selected = os.environ.get ('NAUTILUS_SCRIPT_SELECTED_FILE_PATHS' Curdir = os.environ.get ('NAUTILUS_SCRIPT_CURRENT_URI', os.curdir) if dirname is not None:targets = [dirname] elif selected:targets = selected.splitlines () else:targets = [curdir] for target in targets:if target.startswith (' file:///'):target = target [7:] if not os.path.isdir (target): continuefor dirname, dirnames, files in os.walk (target): for dir in dirnames:dir = os.path.join (dirname) Dir) walk (dir) for file in files:file = os.path.join (dirname, file) if check (file): os.remove (file) if _ _ name__ ='_ _ main__':walk ()
Nautilus extension
The second way to enhance Nautilus is by creating extensions. This method is more complex than the first one, but has many advantages. Nautilus extensions can be embedded in the file display window, so you can write extensions that fill columns with information that you didn't have before. The first thing to do is to install the python-nautilus extension with the following command:
Sudo apt-get install python-nautilus
This command downloads and installs the required files, including documentation and examples. You can find the sample code in the directory / usr/share/doc/python-nautilus/examples. After the installation is complete, you can access a set of Nautilus classes and providers to code it again. Table 2 shows the list.
Table 2. Nautilus classes and vendors
Class or vendor description nautilus.Column reference Nautilus column object nautilus.FileInfo reference Nautilus fileinfo object nautilus.Menu reference Nautilus menu object nautilus.MenuItem reference Nautilus menuitem object nautilus.PropertyPage reference Nautilus propertypage object nautilus.ColumnProvider allows display in the Nautilus column output nautilus.InfoProvider provides information about the file nautilus.LocationWidgetProvider display location nautilus.MenuProvider adds new functionality to the right-click menu nautilus.PropertyPageProvider adds information to the property page
The examples provided on the gnome.org site show the use of MenuProvider (background-image.py and open-terminal.py), ColumnProvider, and InfoProvider (block-size-column.py), and PropertyPageProvider (md5sum-property-page.py). ColumnProvider uses 13 lines of Python executable code to introduce new columns to Nautilus. Once the code is placed in the appropriate directory (~ / .nautilus/python-extensions) and Nautilus has been restarted, you will see a new option when you click View > Visible Columns. The Visible Columns option appears only when the view type is set to List. Enable the Block size column by selecting the check box that shows the results of the following calls to the Python library:
Str (os.stat (filename) .st_blksize))
The basic pattern of any Python extension is to subclass the existing Nautilus provider base class, then execute a series of instructions, and eventually return the appropriate Nautilus object. In the block-size-column.py example, the object returned is nautilus.Column. You must pass four parameters to Nautilus, including name, attribute, label, and description. The Python code for this example is:
Return nautilus.Column ("NautilusPython::block_size_column", "block_size", "Block size", "Get the block size")
Writing code for new extensions involves inheriting information from specific base classes. In the case of block-size-column.py, nautilus.ColumnProvider and nautilus.InfoProvider have examples in the class definition, so the new class inherits from these two places. Next, you need to override any methods from the base class or class to populate the column. In the block-size-column.py example, this can be done by overriding the get_columns and update_file_info methods.
The method of passing information to the Nautilus extension is different from the script example. Nautilus actually starts a new process to execute the script and sets multiple environment variables to convey information. Extensions performed in the same process as Nautilus have access to objects, methods, and properties. File information passed through nautilus.FileInfo, including file_type, location, name, uri, and mime_type. To add information to the FileInfo object, you must call the add_string_attribute method. The following example uses this approach to add new properties to the FileInfo object.
Example: lists the number of lines in the file
The first example uses the PropertyPageProvider method to right-click a file (or files) to display the number of lines and parameters, and then click Properties. The basic idea behind this extension is to calculate the number of lines and parameters in the file and report the results in the new tab of the file property page. The extension has direct access to Nautilus data structures, including file objects. The only thing to do is to use the urllib.unquote library function to open the name, as follows:
Filename = urllib.unquote (file.get_uri () [7:]
Some lines in Python do the main work of counting rows and parameters. For this example, create a count function to read the entire file into a large string, and then calculate the number of parameters and the number of newly added parameters. Because the properties page can be displayed as many selected files and directories, multiple files must be calculated in advance. At this point, the only thing to do is to add the results to the new page on the property page. This example creates a sample gtk.Hbox and then uses the information obtained to populate a large number of tags, as shown in listing 3.
Listing 3. Linecountextension.py file
Import nautilusimport urllibimport gtkimport ostypes = ['.py', '.js', '.html', '.css', '.txt', '.rst', '.cgi'] exceptions = ('MochiKit.js',) class LineCountPropertyPage (nautilus.PropertyPageProvider): def _ _ init__ (self): passdef count (self, filename): s = open (filename). Read () return s.count ('\ n'), len (s) def get_property_pages (self) Files): if not len (files): returnlines = 0chars = 0for file in files:if not file.is_directory (): result = self.count (urllib.unquote (file.get_uri () [7:])) lines + = result [0] chars + = result [1] self.property_label = gtk.Label ('Linecount') self.property_label.show () self.hbox = gtk.HBox (0 False) self.hbox.show () label = gtk.Label ('Lines:') label.show () self.hbox.pack_start (label) self.value_label = gtk.Label () self.hbox.pack_start (self.value_label) self.value_label.set_text (str (lines)) self.value_label.show () self.chars_label = gtk.Label (' Characters:') self.chars_label.show () self.hbox.pack_start (self.chars_) Label) self.chars_value = gtk.Label () self.hbox.pack_start (self.chars_value) self.chars_value.set_text (str (chars)) self.chars_value.show () return nautilus.PropertyPage ("NautilusPython::linecount" Self.property_label, self.hbox)
Figure 3 shows the result of right-clicking on the file and clicking the Linecount tab. At this point, it is important to note that this feature can be used for files or any set of selected files and directories. The numbers reported will represent all lines in all files.
Figure 3. Click the Linecount tab to view the number of lines in the file
Finally, modify the extension function to populate a column instead of the entire property page. As a result, the code changes are relatively small, although you need to inherit from both nautilus.ColumnProvider and nautilus.InfoProvider. You must also execute get_columns and update_file_info. The method get_columns returns only the information obtained by the method count.
The method count uses different techniques for column provider extensions. The readlines routine of Python is used to read all lines of a file into a column of strings. The total number of calculated rows is the number of listing elements returned in the len (s) statement. In both cases, a file type check is performed: this is to ensure that only text files that contain lines that need to be counted are counted. You can use the following lines to create a list of acceptable file extensions:
Types = ['.py', '.js', '.html', '.css', '.txt', '.rst', '.cgi']
The second listing contains exceptions that will not be counted and, in this case, a file with the following lines:
Exceptions = ['MochiKit.js']
These two listings are used to include or exclude files with the following two lines of code:
If ext not in types or basename in exceptions:return 0
The entire extension requires 26 lines of executable code. You may want to modify the extension and enter a list to include or exclude files of interest. Listing 4 shows the complete extension.
Listing 4. Python code for Linecountcolumn extensions
Import nautilusimport urllibimport ostypes = ['.py', '.js', '.html', '.css', '.txt', '.rst', '.cgi'] exceptions = ['MochiKit.js'] class LineCountExtension (nautilus.ColumnProvider, nautilus.InfoProvider): def _ init__ (self): passdef count (self) Filename): ext = os.path.splitext (filename) [1] basename = os.path.basename (filename) if ext not in types or basename in exceptions:return 0s = open (filename). Readlines () return len (s) def get_columns (self): return nautilus.Column ("NautilusPython::linecount", "linecount", "Line Count", "The number of lines of code"), def update_file_info (self File): if file.is_directory (): lines = 'n/a'else:lines = self.count (urllib.unquote (file.get_uri () [7:])) file.add_string_attribute (' linecount', str (lines))
Figure 4 shows the Nautilus window with the Line Count column enabled. Each individual file shows the total number of lines. You need to use this method to do a calculation to know how many files you need.
Figure 4. Line Count column in the Nautilus window
Thank you for reading this article carefully. I hope the article "how to expand and extend Nautilus with Python" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.