📜 ⬆️ ⬇️

Python vs. Bash scripts - 2 or Tips & Tricks

image
Quite a while ago I wrote an article in which I gave examples of the basics of working with the system using Python scripts. Because of the glimpse of the dropped phrase (just look at the name of the topic), the article received quite a lot of comments of a holivar and not very character. Someone might have wanted to take advantage of Python for administration (now this kind of python tool is just gaining popularity). So why not lure some more like-minded people to your camp? :) Meet - a small selection of simple techniques for those or other purposes.

Files and something else


So, right off the bat! First, let's take a banal procedure - copying a file. I still remember this horror that I had to write on bare C - reading a file line by line into a variable and rewriting it at a different address ... But you can easily use more simple methods! :) The first way that a Linux user comes to mind is most likely something like
Copy Source | Copy HTML import subprocess subprocess .Popen( 'cp /usr/share/file.txt /home/user/file.txt' , shell=True)
  1. Copy Source | Copy HTML import subprocess subprocess .Popen( 'cp /usr/share/file.txt /home/user/file.txt' , shell=True)
  2. Copy Source | Copy HTML import subprocess subprocess .Popen( 'cp /usr/share/file.txt /home/user/file.txt' , shell=True)

Only here such a method will work only if there is a bash or similar interpreter (well, or it requires prescription of aliases). What for? After all, you can use the excellent shutil module method:
Copy Source | Copy HTML
  1. import shutil
  2. shutil .copyfile ( "C: \\ My Documents \\ mydoc.doc" , "C: \\ My Documents \\ mydoc_2.doc" )

Renaming is done in a similar way:
Copy Source | Copy HTML
  1. import os
  2. os .rename ( "/home/user/testfile.txt" , "/home/user/test.txt" )

You can delete a file, respectively, using os.remove () .

To write data to a file, you can use both the python write () and the “stream” version (hippoplus, hello to you):
Copy Source | Copy HTML
  1. myfile = open ( "/home/user/testfile.txt" , "w" )
  2. print >> myfile, "I want to drink some beer with Guido"
  3. myfile.close ()

upd: More modern method from username image bioroot (enabled by default only starting from version 2.6, in 2.5 it can be taken from __future__:
>> from __future__ import with_statement):
Copy Source | Copy HTML
  1. with open ( "/home/user/testfile.txt" , "w" ) as myfile:
  2. print >> myfile, "I want to drink some beer with Guido"


Sometimes (for example, when reading logs) you may need to read a file line by line, starting from the end. This is done elementary:
Copy Source | Copy HTML
  1. for line in reversed ( open ( "/ var / log / messages" ). readlines ()):
  2. print line

And to read a line under a certain number — you can use both the standard file reading per sheet and the linecache module:
Copy Source | Copy HTML
  1. line = linecache .getline ( "C: \\ test.txt" , 2 )
  2. print line
  3. # or
  4. line = open ( "C: \\ test.txt" ). readlines () [ 1 ]
  5. print line

By the way, a binary file is no more difficult to read:
Copy Source | Copy HTML
  1. pic = open ( "C: \\ Pictures \\ V4erashnaya_pyanka.bmp" , "rb" )
  2. buf = pic.read ( 5 ) # read the first 5 bytes
  3. print buf

In addition, in order not to get lost:
Copy Source | Copy HTML
  1. print pic.tell () # number of bytes from the beginning of the file
  2. pic.seek (0) # back to top

')
If, for example, we write a program with plug-in support, we may need to search through files in a specific directory:
Copy Source | Copy HTML
  1. for filename in os .listdir ( "../plugins" ):
  2. print (filename)

And you can do the same for the mask:
Copy Source | Copy HTML
  1. import glob
  2. for filename in glob . glob ( "../plugins/*.zip" ):
  3. print filename

Parsim of the way:
Copy Source | Copy HTML
  1. print os .path.dirname ( "/home/user/test.txt" ) # directory name
  2. print os .path.basename ( "/home/user/test.txt" ) # filename

Open the address or local file in the default browser (for example, when creating links in about-windows):
Copy Source | Copy HTML
  1. import webbrowser
  2. webbrowser . open ( 'http://www.habrahabr.ru/' )
  3. webbrowser . open (u 'file: //home/user/mysite.html' )
  4. webbrowser . open (u 'mailto: foo@bar.com? subject = Feedback% 20message' )

To determine the encoding of a string or file, you can use the convenient chardet module, and not only the encoding is returned, but also the “confidence” that it is defined correctly in a beautiful dictionary:
Copy Source | Copy HTML
  1. import chardet
  2. str = open ( "/home/user/myfile.txt" , "r" ). readline ()
  3. enc = chardet.detect (str)
  4. print enc [ 'confidence' ]
  5. print enc [ 'encoding' ]

A very handy thing when you need, for example, to bind a string with a previously unknown encoding. True, I ran into the problem of defining mac-encodings (simple ascii is always returned, but he and Mac, that some of the characters are not encoded as usual). In any case, linuksoidam is easier - we have enca and iconv :)

Well, while enough? If you like the trend, I’ll try to continue the description of how to use Python to administer the system and write a couple of working examples. And yes, thank you so much for such a thing as a Python Cookbook!

Source: https://habr.com/ru/post/62383/


All Articles