воскресенье, 10 июля 2016 г.

Как обойти дерево директорий на языке Python – руководство к os.walk

Основы проход директорий на языке Python

Здесь приведен очень простой пример обхода дерево директорий, печать имен директорий и списка файлов в каждой из них:
1
2
3
4
5
6
7
8
9
# Import the os module, for the os.walk function
import os

# Set the directory you want to start from
rootDir = '.'
for dirName, subdirList, fileList in os.walk(rootDir):
    print('Found directory: %s' % dirName)
    for fname in fileList:
        print('\t%s' % fname)




os.walk скрывает детали и на каждом проходе цикла выдает три объекта:
  • dirName: следующую найденную директорию.
  • subdirList: список поддиректорий в текущей директории.
  • fileList: список файлов в текущей директории.
Рассмотрим пример директории:
+--- test.py
|
+--- [subdir1]
|     |
|     +--- file1a.txt
|     +--- file1b.png
|
+--- [subdir2]
|
+--- file2a.jpeg
+--- file2b.html
Код программы выведет следующее:
1
2
3
4
5
6
7
8
Found directory: .
file2a.jpeg
file2b.html
test.py
Found directory: ./subdir1
file1a.txt
file1b.png
Found directory: ./subdir2

понедельник, 4 июля 2016 г.

Как записать в файл русские символы в Python?

В python 3 на Windows функция locale.getpreferredencoding(False) возвращает 'cp1251'. Именно с этой кодировкой открывается новый файл по умолчанию, и, как следствие, к ней приводятся строки, записываемые в этот файл.

Если просмотреть директории на диске с помощью os.walk(), то эта функция вернет набор директорий и имен файлов. Если эти имена у вас на русском языке и вы захотели записать их в файл, у вас проблема.

Решение: открывать файл с опцией кодирования файла как 'utf-8':
with open(logname, 'w', encoding='utf-8') as logfile:
   ...

  

Проверка существует ли файл в папке на языке Python

Проверка существует ли файл в папке на языке Python

1. os.path.isfile(path)

Эта функция возвращает true, если данный путь является существующим обычным файлом. Из этого следует, что символические связи (symbolic links) в виде os.path.islink(path) тоже будут true пока os.path.isfile(path) также будет true. Это удобная функция, что бы проверить существует ли файл. К сожалению эта функция только проверяет наличие файла, но не гарантирует имеет ли пользователь доступ к этому файлу. Она говорит вам, что файл существует точно в момент вызова функции. Вполне возможно (хотя не хотелось бы), что во время между тем как вызвал функцию и открываешь файл, его кто-то удалил и перенес/переименовал.
Например, здесь показан такой случай неудачного открытия файла:
1
2
3
4
5
6
>>> os.path.isfile('foo.txt')
True
>> f = open('foo.txt', 'r')
Traceback (most recent call last):
File "", line 1, in
IOError: [Errno 13] Permission denied: 'foo.txt'

2. os.access(path, mode)

Эта функция проверяет имеет ли текущий пользователь (с реальным uid/gid) доступ (привилегии на чтение и/или запись) к объекту с данным путем. Чтобы проверить этот файл доступен на чтение используют режим os.R_OK, а на запись используют режим os.W_OK. Например.
1
2
3
4
5
6
7
>>> # Check for read access to foo.txt
>>> os.access('foo.txt', os.R_OK)
True # This means the file exists AND you can read it.
>>>
>>> # Check for write access to foo.txt
>>> os.access('foo.txt', os.W_OK)
False # You cannot write to the file. It may or may not exist.
Если вы планируете получить доступ к файлу, использование этой функции обезопасит вас попытка доступа к не разрешенного для вас файла. Но возможность того, что в период между проверкой разрешенного доступа и физическим открытием кто-то удалит или переименует файл остается.
1
2
3
4
5
6
7
8
>>> # The file 'foo.txt' currently exists and is readable.
>>> if os.access('foo.txt', os.R_OK):
>>> # After executing os.access() and before open(),
>>> # another program deletes the file.
>>> f = open('foo.txt', 'r')
Traceback (most recent call last):
File "", line 1, in
IOError: [Errno 2] No such file or directory: 'foo.txt'

3. Доступ к файлу (открытие файла).

Попытавшись открыть файл, вы не только убедитесь, что файл существует но и доступен для вас.
1
2
3
4
5
try:
f = open('foo.txt')
f.close()
except IOError as e:
print('Упс!')
Этот код можно легко трансформировать в функцию.
1
2
3
4
5
6
7
8
9
def file_accessible(filepath, mode):
''' Проверка существует ли файл и доступен ли. '''
try:
f = open(filepath, mode)
f.close()
except IOError as e:
return False


return True
Например, ее можно использовать следующим образом:
1
2
3
4
5
6
7
>>> # Say the file 'foo.txt' exists and is readable,
>>> # whereas the file 'bar.txt' doesn't exist.
>>> foo_accessible = file_accessible('foo.txt', 'r')
True
>>>
>>> bar_accessible = file_accessible('bar.txt', 'r')
False

Jackson Cooper 

 

суббота, 7 мая 2016 г.

Windows 10 и я

Вот уже полгода как перешел на windows 10 по предложению Microsoft с лицензионной семерки. Все прошло нормально. Работают все приложения. Мне кажется, что стал работать быстрее, особенно с USB. Так как дистрибутива нет, установка шла по Интернету, сделал backup системы на USB флэшку.(5 Гб)

06.12.2016 И вот оно пришло-компьютер сдох, намертво. Жмешь на кнопочки, а он не реагирует! Подозрение на материнскую плату- блок питания скрепкой запустился, кнопка запуска тестором замыкает контакт. Скрепя сердцем сделал апгрейд: заменил материнку, процессор и память. Вставил в старый корпус, а в ответ ТИШИНА. Помучившись с мертвым "телом" друга, решил заменить корпус и блок питания. После этой замены, компьютер стал подниматься на старых дисках. При загрузке вошел в setup bios и указал с которого диска грузиться. Система поднялась, но активация слетела. На мои муки отвечала устойчиво ошибка активизации.

Вышел на связь с поддержкой Microsoft по чату. И мне посоветовали: вводим Win+r, в командной строке вводим slui 3, в открывшемся окне вводим код продукта из коробочки Windows 7 (купленной). Далее произошла активация системы.     

понедельник, 22 февраля 2016 г.

Final Firmware FW 2.6 for X5 1St Gen и W40

Наконец появилось обновление для моего FIIO X5 под номером 2.6 и нестабильность при выборе пунктов меню кнопкой ОК УШЛА! Я так рад и ВСЕМ рекомендую установить это обновление!
  
 Final Firmware FW 2.6 for X5 1St Gen
http://www.fiio.net/en/story/330

Слушаю плеер Fiio X5 с наушниками Westone W40. Отличный звук!
Кстати, кому мало басов, поэкспериментируйте с амбушюрами.

Сначала были Westone 3 и плеер Colorfly C3. Носил в портфеле. Провод обмотан вокруг плеера. Сам плеер небольшой, из металла и увесистый. Както сел в вагон электрички, стал доставать плеер. Он выскользнул из рук и упал. Углом он перебил провод наушников, намотанный вокруг корпуса. Провода у Westone 3 запрессованы в корпус наушника и замене не подлежат. Одно расстройство.
Тогда я понял почему у наушников должны быть съемные провода!

Кстати у съемных проводов W40 маркировка такая: одна точка это правый канал(второй с низу элемент штекера); две точки это левый канал(самый нижний элемент штекера); самый верхний элемент штекера это общий провод.

Купил Westone W40 и Fiio X5. Жизнь снова полна музыки.

Провод у "старых" W3 спаял и обмотал изолентой. Иногда пользуюсь. 


вторник, 26 января 2016 г.

A cx_Freeze Tutorial – Build a Binary Series!

A cx_Freeze Tutorial – Build a Binary Series!

В этой статье, мы рассмотрим cx_Freeze, набор скриптов для разных платформ и цель их "заморозить" скрипты Python в исполняемый файл аналогично py2exe, PyInstaller, и т.д.. We will freeze one console script and one window (i.e GUI) script, using the examples from the previous article in this series. If you haven’t done so already, you can get cx_Freeze here. Let’s get this party started, shall we?

Getting Started with cx_Freeze

As mentioned on the cx_Freeze website, there are three ways to use this script. The first is to just use the included cxfreeze script; the second is to create a distutils setup script (think py2exe) which you can save for future use; and the third is to work with the internals of cxfreeze. We will focus on the first two ways of using cx_Freeze. We’ll begin with the console script:

import configobj
 
#----------------------------------------------------------------------
def createConfig(configFile):
    """
    Create the configuration file
    """
    config = configobj.ConfigObj()
    inifile = configFile
    config.filename = inifile
    config['server'] = "http://www.google.com"
    config['username'] = "mike"
    config['password'] = "dingbat"
    config['update interval'] = 2
    config.write()
 
#----------------------------------------------------------------------
def getConfig(configFile):
    """
    Open the config file and return a configobj
    """    
    return configobj.ConfigObj(configFile)
 
def createConfig2(path):
    """
    Create a config file
    """
    config = configobj.ConfigObj()
    config.filename = path
    config["Sony"] = {}
    config["Sony"]["product"] = "Sony PS3"
    config["Sony"]["accessories"] = ['controller', 'eye', 'memory stick']
    config["Sony"]["retail price"] = "$400"
    config.write()
 
if __name__ == "__main__":
    createConfig2("sampleConfig2.ini")
 
 
All this script does is create a really simple configuration file using Michael Foord’s configobj module. You can set it up to read the config too, but for this example, we’ll skip that. Let’s find out how to build a binary with cx_Freeze! According to the documentation, all it should take is the following string on the command line (assuming you are in the correct directory):

cxfreeze config_1.py --target-dir dirName

This assumes that you have “C:\PythonXX\Scripts” on your path. If not, you’ll either have to fix that or type out the fully qualified path. Anyway, if the cxfreeze script run correctly, you should have a folder with the following contents:





http://www.blog.pythonlibrary.org/wp-content/uploads/2010/08/cx_freeze_dir.png

As you can see, the total file size should be 4.81 MB or almost 5 megabytes. That was pretty easy. It even picked up the configobj module without our having to tell it to, something that PyInstaller failed to do. There are 18 command line arguments you can pass to cx_Freeze to control how it does things. These range from what modules to include or exclude, optimization, compression, include a zip file, path manipulation and more. Now let’s try something a little more advanced.

“Advanced” cx_Freeze – Using a setup.py File

First off we need a script to use. For this one, we’ll use that simple wxPython script from the PyInstaller article:

import wx
 
########################################################################
class DemoPanel(wx.Panel):
    """"""
 
    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
 
        labels = ["Name", "Address", "City", "State", "Zip",
                  "Phone", "Email", "Notes"]
 
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        lbl = wx.StaticText(self, label="Please enter your information here:")
        lbl.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD))
        mainSizer.Add(lbl, 0, wx.ALL, 5)
        for lbl in labels:
            sizer = self.buildControls(lbl)
            mainSizer.Add(sizer, 1, wx.EXPAND)
        self.SetSizer(mainSizer)
        mainSizer.Layout()
 
    #----------------------------------------------------------------------
    def buildControls(self, label):
        """"""
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        size = (80,40)
        font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD)
 
        lbl = wx.StaticText(self, label=label, size=size)
        lbl.SetFont(font)
        sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
        if label != "Notes":
            txt = wx.TextCtrl(self, name=label)
        else:
            txt = wx.TextCtrl(self, style=wx.TE_MULTILINE, name=label)
        sizer.Add(txt, 1, wx.ALL, 5)
        return sizer
 
 
 
########################################################################
class DemoFrame(wx.Frame):
    """
    Frame that holds all other widgets
    """
 
    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""        
        wx.Frame.__init__(self, None, wx.ID_ANY, 
                          "cxFreeze Tutorial",
                          size=(600,400)
                          )
        panel = DemoPanel(self)        
        self.Show()
 
#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = DemoFrame()
    app.MainLoop()
 
Now let’s create a setup.py file in the cx_Freeze style:
from cx_Freeze import setup, Executable   setup( name = "wxSampleApp", version = "0.1", description = "An example wxPython script", executables = [Executable("sampleApp.pyw")] ) As you can see, this is a pretty simple one. We import a couple classes from cx_Freeze and pass some parameters into them. In this case, we give the setup class a name, version, description and and Executable class. The Executable class also gets one parameter, the script name that it will use to create the binary from. To get this to build the binary, you need to do the following on the command line:

python setup.py build

After running this, you should end up with the following folders: “build\exe.win32-2.6″. Inside that last folder are 17 files that total 15.3 MB. When you run the sampleApp.exe file, you will notice that we’ve screwed something up. There’s a console window loading in addition to our GUI!!! To rectify this, we’ll need to change our setup file slightly. Take a look at our new one:
from cx_Freeze import setup, Executable   exe = Executable( script="sampleApp.pyw", base="Win32GUI", )   setup( name = "wxSampleApp", version = "0.1", description = "An example wxPython script", executables = [exe] ) First off, we separated the Executable class from the setup class and assigned the Executable class to a variable. We also added a second parameter to the Executable class that is key. That parameter is called “base”. By setting base=”Win32GUI”, we are able to suppress the console window. A good way to learn the many other options that we can use with cx_Freeze is to use GUI2Exe to generate the setup.py files for us. The documentation on the cx_Freeze website shows the many other options that the Executable class takes. Oddly enough, I couldn’t find any information about what the setup class takes for arguments other than just the source itself, which has very little comments. Good luck figuring that bit out.

Wrapping Up

Now you should know how to create binaries with cx_Freeze. It’s pretty easy to do and it’s nice that they’ve created a method to create binaries in a cross-platform way. Have fun!
 

пятница, 22 января 2016 г.

Про Python

Если вы используете Python, то просто необходима программа pip.exe. Пакеты можно поставить введя в командной строке pip install имя_пакета. Командную строку необходимо запускать от Администратора.
Выполнить обновления этой программы можно командой:
python -m pip install --upgrade pip 

Чтобы узнать какие из установленных пакетов просрочены введите команду:
pip list -o

Из этого списка узнаете имена пакетов, для которых имеются обновления. Их обновить можно командой:
pip install -U имя_пакета4.5.

У меня Python 3.5 и PyDev 5.1.2 в Eclipse  4.5.2 (MARS), Windows 10 Home 64 bits. Я поставил PyQT5 при помощи команды pip install PyQT5. Затем в описании переменной среды операционной системы PATH вставил путь к папке PyQT5:
C:\Program Files\Python 3.5\Lib\site-packages\PyQt5
В PyDev, в настройках интерпретатора Python в окне Libraries добавил строку C:\Program Files\Python 3.5\Lib\site-packages\PyQt5. В окне Forced Builtins добавил имя пакета PyQt5.
Нажал ОК - подождал пока Eclipse обновит свою переменную PYTHONPATH. И после перезагрузки Eclipse можно работать с PyQt5 и главное работает авто заполнение!

X-Plane 11, 12 - любитель, Фото любитель со стажем

Постоянные читатели

Архив блога