Python port for windows

pySerial¶

This module encapsulates the access for the serial port. It provides backends for Python running on Windows, OSX, Linux, BSD (possibly any POSIX compliant system) and IronPython. The module named “serial” automatically selects the appropriate backend.

It is released under a free software license, see LICENSE for more details.

Copyright (C) 2001-2020 Chris Liechti

Features¶

  • Same class based interface on all supported platforms.
  • Access to the port settings through Python properties.
  • Support for different byte sizes, stop bits, parity and flow control with RTS/CTS and/or Xon/Xoff.
  • Working with or without receive timeout.
  • File like API with “read” and “write” (“readline” etc. also supported).
  • The files in this package are 100% pure Python.
  • The port is set up for binary transmission. No NULL byte stripping, CR-LF translation etc. (which are many times enabled for POSIX.) This makes this module universally useful.
  • Compatible with io library
  • RFC 2217 client (experimental), server provided in the examples.

Requirements¶

  • Python 2.7 or Python 3.4 and newer
  • If running on Windows: Windows 7 or newer
  • If running on Jython: “Java Communications” (JavaComm) or compatible extension for Java

For older installations (older Python versions or older operating systems), see older versions below.

Installation¶

This installs a package that can be used from Python ( import serial ).

Читайте также:  Http ru bans php

To install for all users on the system, administrator rights (root) may be required.

From PyPI¶

pySerial can be installed from PyPI:

python -m pip install pyserial 

Using the python / python3 executable of the desired version (2.7/3.x).

Developers also may be interested to get the source archive, because it contains examples, tests and the this documentation.

From Conda¶

pySerial can be installed from Conda:

conda install pyserial or conda install -c conda-forge pyserial 

Currently the default conda channel will provide version 3.4 whereas the conda-forge channel provides the current 3.x version.

From source (zip/tar.gz or checkout)¶

Download the archive from http://pypi.python.org/pypi/pyserial or https://github.com/pyserial/pyserial/releases. Unpack the archive, enter the pyserial-x.y directory and run:

Using the python / python3 executable of the desired version (2.7/3.x).

Packages¶

There are also packaged versions for some Linux distributions:

  • Debian/Ubuntu: “python-serial”, “python3-serial”
  • Fedora / RHEL / CentOS / EPEL: “pyserial”
  • Arch Linux: “python-pyserial”
  • Gentoo: “dev-python/pyserial”

Note that some distributions may package an older version of pySerial. These packages are created and maintained by developers working on these distributions.

References¶

Older Versions¶

Older versions are still available on the current download page or the old download page. The last version of pySerial’s 2.x series was 2.7, compatible with Python 2.3 and newer and partially with early Python 3.x versions.

pySerial 1.21 is compatible with Python 2.0 on Windows, Linux and several un*x like systems, MacOSX and Jython.

On Windows, releases older than 2.5 will depend on pywin32 (previously known as win32all). WinXP is supported up to 3.0.1.

© Copyright 2001-2020, Chris Liechti Revision 31fa4807 .

Versions latest stable Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

port-for 0.7.1

Utility that helps with local TCP ports management. It can find an unused TCP localhost port and remember the association.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License (Copyright (c) 2012 Mikhail Korobov Permission is hereby granted, free of charge, to any person obta. )

Сопровождающий: Grzegorz Śliwiński

Требует: Python >=3.7

Сопровождающие

Классификаторы

Описание проекта

port-for is a command-line utility and a python library that helps with local TCP ports management.

It can find an unused TCP localhost port and remember the association:

This can be useful when you are installing a stack of software with multiple parts needing port numbers.

If you’re looking for a temporary port then socket.bind((host, 0)) is your best bet:

>>> import socket >>> s = socket.socket() >>> s.bind(("", 0)) >>> s.getsockname() ('0.0.0.0', 54485)

port-for is necessary when you need persistent free local port number.

port-for is the exact opposite of s.bind((host, 0)) in the sense that it shouldn’t return ports that s.bind((host, 0)) may return (because such ports are likely to be temporary used by OS).

There are several rules port-for is trying to follow to find and return a new unused port:

  1. Port must be unused: port-for checks this by trying to connect to the port and to bind to it.
  2. Port must be IANA unassigned and otherwise not well-known: this is acheived by maintaining unassigned ports list (parsed from IANA and Wikipedia).
  3. Port shouldn’t be inside ephemeral port range. This is important because ports from ephemeral port range can be assigned temporary by OS (e.g. by machine’s IP stack) and this may prevent service restart in some circumstances. port-for doesn’t return ports from ephemeral port ranges configured at the current machine.
  4. Other heuristics are also applied: port-for tries to return a port from larger port ranges; it also doesn’t return ports that are too close to well-known ports.

Installation

System-wide using easy_install (something like python-setuptools should be installed):

sudo easy_install port-for

Script usage

port-for script finds an unused port and associates it with . Subsequent calls return the same port number.

This utility doesn’t actually bind the port or otherwise prevents the port from being taken by another software. It tries to select a port that is less likely to be used by another software (and that is unused at the time of calling of course). Utility also makes sure that port-for bar won’t return the same port as port-for foo on the same machine.

$ sudo port-for foo 37987 $ port-for foo 37987

You may want to develop some naming conventions (e.g. prefix your app names) in order to enable multiple sites on the same server:

$ sudo port-for example.com/apache 35456

Please note that port-for script requires read and write access to /etc/port-for.conf . This usually means regular users can read port values but sudo is required to associate a new port.

List all associated ports:

$ port-for --list foo: 37987 example.com/apache: 35456
$ sudo port-for --unbind foo $ port-for --list example.com/apache: 35456

Library usage

>>> import port_for >>> port_for.select_random() 37774 >>> port_for.select_random() 48324 >>> 80 in port_for.available_good_ports() False >>> port_for.get_port() 34455 >>> port_for.get_port("1234") 1234 >>> port_for.get_port((2000, 3000)) 2345 >>> port_for.get_port() 4005 >>> port_for.get_port([, (4100, 4200)]) 4111

Dig into source code for more.

Contributing

Release

Install pipenv and –dev dependencies first, Then run:

pipenv run tbump [NEW_VERSION]

Источник

Доступ к портам с использованием WinApi и dll из Python

Предыдущие реализации на Питоне аналога проприетарного софта, оказались вполне ничего себе, т. е. все работает, и все похоже на Excel, а значит endusers будут довольны-). Дальнейший простор для полета фантазии немного сдерживается невозможностью доступа к более детальным настройкам портов из стандартных модулей. Но оказывается в Питоне есть такая изумительная вещь как доступ к WinApi функциям, что расширяет перспективы чуть ли не до Cpp-шных. Причем это касается не только портов, а еще кучи всяких вещей. Список и краткое описание поддерживаемых WinApi функций для Питона здесь-
docs.activestate.com/activepython/3.3/pywin32/win32file.html, прорва примеров на Nullege здесь — nullege.com/codes/search/win32file и здесь www.programcreek.com/python/index/1133/win32file, ну и как это принято в Питоне избавление от несовершенства модулей — доступ к WinApi функциям, осуществляется через модуль-) — win32file,- соответственно — pip install win32file.
Вот например как может выглядеть настройка и работа Com порта —
сначала понятно импортируем модуль:

import win32file

hFile = win32file.CreateFile(«COM2», win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0,None,win32file.OPEN_EXISTING, 0,None)

тут разница в названиях — стандартным предшествует ‘win32file.’, и вместо NULLNone
(в названии порта кавычки верхние см. рис. и комменты).
Далее аналогично стандартным процедурам, например в Visual Studo — структура настройки — создаем:

comDCB = win32file.DCB()

comDCB.ByteSize = 8
comDCB.Parity = win32file.NOPARITY
comDCB.StopBits = win32file.ONESTOPBIT
comDCB.BaudRate = 9600

записываем:

win32file.SetCommState(hFile,comDCB)

рамер входного/выходного буфера:

win32file.SetupComm(hFile, 4096, 4096)

вот например маска(1) по приему первого байта, то чего нет в стандартном модуле pyserial:

win32file.SetCommMask(hFile, 1)

win32file.WaitCommEvent(hFile, None)

buff=’пишем чего-нибудь-)’

не забываем, что передаем поток байт — переконвертируем строку в массив байт:

ttt=bytearray(buff, encoding=’cp1251′)

win32file.WriteFile(hFile,ttt,None)

ждем эвента по приему первого байта и читаем 19 байт:

win32file.WaitCommEvent(hFile, None)
win32file.ReadFile(hFile, 19)



ну и закрыть:

win32file.CloseHandle(hFile)

C LPT все немного по-другому, хотя и можно создать хэндл как показано выше — запись и чтение в файл повидимому приведет к обращению к стандартному драйверу и невозможности записи без получения ‘ASK’ от ‘принтера’. Поэтому, как мне кажется, более удобное — широко известное решение — inpout32.dll.
Для возни с параллельным портом я использую следующий гипердевайс-

по мотивам того, который был представлен на pcports — www.kernelchip.ru/pcports/PS005.php Повторять мне было лень, я сделал проще — задействованы два регистра из трех — чтения нет(регистр Status не задействован). Питание светодиодов счетверенного семисегментного индикатора от высокого состояния одного порта и низкого состояния другого. Такая схема дает возможность использовать динамическую индикацию и оценить быстродействие разных способов вывода через порт, но… не будем забегать вперед-) Итак, пока просто выведем циферку скажем ‘7’ на второй индикатор:
from ctypes import windll
p = windll.LoadLibrary(«C:\Python34\DLLs\inpout32.dll»)
p.Out32(890, 9)
p.Out32(888, 241)

(в названии пути кавычки верхние см. рис. и комменты)

функция возвращает 1 — типа все нормально-)

тут только одно тонкое место, часть выводов в регистре ‘Control’ инвертирована — ru.wikipedia.org/wiki/Параллельный_порт и это надо учитывать.

Ну и в заключение небольшой сравнительный тест результаты которого меня просто поразили. Две аналогичные программы — на старом VC6 и на Python — функционально это динамическая индикация через LPT порт. В VC6 в обработчике таймера производится пересчет(преобразование) числа в первом окошке в семисегментный код, во втором окне — задается время переключения (таймера). Запуск преобразования кнопка ‘Start indicate’, остановка — ‘Stop’.

В Питоне все аналогично, но таймеров там нет и задержка реализована функцией time.sleep(timer) где timer — время в секундах, в VC6 время задается в миллисекундах. В Питоне в отдельном потоке функции вывода и задержки в бесконечном цикле, в VC функция вывода(такая же как в Питоне) в обработчике таймера, — по каждому срабатыванию выводит по одной цифре. Ну в общем все как обычно, и программная реализация самостоятельного интереса не представляет. А представляет интерес результат — скорости вывода( на вид естественно ) идентичны (. ), т. е. шустрый питонский байт код, в этих конкретных условиях вполне такой же быстрый как и сишный компиллированный. Вообще-то из-за того что таймер в VC6 вообще нельзя поставить меньше 10 мс(поставить-то можно, толку не будет), а в Питоне задержку можно и 0.001 с, то Питон еще и быстрее, что собственно и видно при последнем включении с задержкой 0.001 с. на видео. Да, и отдельно прошу извинить за качество фоток и видео— снимал телефоном, более того когда снимал, если кто обратил внимание)), задержка в питонской программе стояла в два раза больше чем в сишной (т.е смена цифр была в два раза медленнее — забыл убрать вторую задержку во время отладки — сейчас конечно убрал), будет возможность видео пересниму. Если, что исходник питонской программы внизу, и заодно видео файлом.
P.S. Добавляю ссылку на видео — переснять не получится — слегка спалил LPT порт -(

Источник

Оцените статью