SlideShare une entreprise Scribd logo
1  sur  32
Télécharger pour lire hors ligne
How to make friends of
Python and Win32 API
Connecting the Python to a Win32 API
provided by a stock broker
What was expected
Terms
Real world
?
Issues
● COM to pure Python object conversion
● Flow (events, async methods) handling
● Multithreading support
● Extensibility
Envisioned solution
Or...
What I’ve found
● pywin32 package on sourceforge.net by Mark Hammond
● python interpreter builds: ActiveState, Anaconda, Canopy
with pywin32
● Python Programming On Win32 by Mark Hammond and
Andy Robinson
● no actual documentation on activestate.com
Pywin32 workflow
Make Handle
Events class
Make client object
with
DispatchWithEven
ts method
Use API
methods on
python object
Python client structure
Event class
class ClientEvents:
def OnAddBar(self, row, nrows, symbol,
interval, datetime, open, high, low, close,
volume, open_int):
pass # some logic
…
Client
clnt =
client.DispatchWithEvents('COM.Server.1',
ClientEvents)
…
clnt.GetBars('SBER', bar_interval,
date_time_object, 10)
Cool tool
Make folder
python_folderLibsite-packageswin32comgen_py
Run 'win32comclientmakepy.py' (eg, run it from the
command window, or double-click on it) and a list will be
presented. Select the Type Library.
It will generate python wrapper classes from COM Library
with all available methods.
Convert DateTime objects
def pytime_2_datetime(pythime):
return dt(year=pythime.year,
month=pythime.month, day=pythime.day,
hour=pythime.hour, minute=pythime.minute,
second=pythime.second)
def datetime_2_pytime(datetime):
return pywintypes.Time(time
.mktime(datetime.timetuple()))
Solution v. 0.1
● COM to pure
Python object
conversion
● Flow (events, async
methods) handling
Issues:
● Multithreading support
● Extensibility
● Not stable (?)
Manager
Workflow
Add event
queue
Create custom
Manager
Make proxy to
COM Object
Get pure python
Events queue
Use proxy and
queue from
other threads
Modify Event class, part 1
class ClientEvents:
def __init__(self):
self.event_queue = Manager().Queue()
def get_event_queue(self):
return self.event_queue
…
Modify Event class, part 2
class ClientEvents:
…
def OnAddBar(self, row, nrows, symbol,
interval, datetime, open, high, low, close,
volume, open_int):
self.event_queue.put_nowait(('AddBar',
row, nrows, symbol, interval,
pytime_2_datetime(datetime), open, high, low,
close, volume, open_int))
Use multiprocessing.Manager
class ComManager(BaseManager):
pass
Add client method
def get_com_server():
CoInitializeEx(COINIT_MULTITHREADED)
clnt =
client.DispatchWithEvents('COM.Server.1',
ClientEvents)
CoUninitialize()
return clnt
Register methods
ComManager.register('get_com_server',
callable=get_com_server,
exposed=('CancelBidAsks',
'CancelOrder',
'GetBars',
'GetMoneyAccount', …,
'get_event_queue'))
Fix DateTime bug, part 1
class ClientEvents:
def GetBarsSer(self, symbol, interval,
since, count):
self.GetBars(symbol, interval,
datetime_2_pytime(since), count)
Fix DateTime bug, part 2
ComManager.register('get_com_server',
callable=get_com_server,
exposed=('CancelBidAsks',
'CancelOrder',
'GetBars',
'GetMoneyAccount', …,
'get_event_queue',
'GetBarsSer'))
Connection server solution
Use as server, server code
if __name__ == '__main__':
freeze_support()
m = ComManager(address=('127.0.0.1', port,
authkey='authkey').get_server()
.serve_forever()
Use as server, client code
…
manager = ComManager(address='address', port,
authkey='authkey')
manager.connect()
com_server =manager.get_com_server()
com_event_queue =
com_server.get_event_queue()
Stand-alone
In code use
from package_mame import ComManager
if __name__ == '__main__':
freeze_support()
manager = ComManager()
manager.start()
com_server = manager.get_com_server()
com_event_queue =
com_server.get_event_queue()
Solution
v. 0.2
Contacts
Linkedin: https://linkedin.com/in/eugene-lopatkin
E-mail: eugenelopatkin@gmail.com
Thank you! Any questions?

Contenu connexe

Similaire à How to make friends python with win32 api

Qtp not just for gui anymore
Qtp   not just for gui anymoreQtp   not just for gui anymore
Qtp not just for gui anymore
Pragya Rastogi
 
Event and signal driven programming
Event and signal driven programmingEvent and signal driven programming
Event and signal driven programming
Elizabeth Smith
 
Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012
Elizabeth Smith
 
VC++ Fundamentals
VC++ FundamentalsVC++ Fundamentals
VC++ Fundamentals
ranigiyer
 
Understanding JavaScript Event-based Interactions
Understanding JavaScript Event-based InteractionsUnderstanding JavaScript Event-based Interactions
Understanding JavaScript Event-based Interactions
SALT Lab @ UBC
 
Dynamic languages for .NET CLR
Dynamic languages for .NET CLRDynamic languages for .NET CLR
Dynamic languages for .NET CLR
py_sunil
 
MLOps Case Studies: Building fast, scalable, and high-accuracy ML systems at ...
MLOps Case Studies: Building fast, scalable, and high-accuracy ML systems at ...MLOps Case Studies: Building fast, scalable, and high-accuracy ML systems at ...
MLOps Case Studies: Building fast, scalable, and high-accuracy ML systems at ...
Masashi Shibata
 

Similaire à How to make friends python with win32 api (20)

How to make friends python with win32 api
How to make friends python with win32 apiHow to make friends python with win32 api
How to make friends python with win32 api
 
Qtp not just for gui anymore
Qtp   not just for gui anymoreQtp   not just for gui anymore
Qtp not just for gui anymore
 
2006 - Basta!: Advanced server controls
2006 - Basta!: Advanced server controls2006 - Basta!: Advanced server controls
2006 - Basta!: Advanced server controls
 
Apache Flink @ NYC Flink Meetup
Apache Flink @ NYC Flink MeetupApache Flink @ NYC Flink Meetup
Apache Flink @ NYC Flink Meetup
 
Flink Forward Berlin 2017: Patrick Gunia - Migration of a realtime stats prod...
Flink Forward Berlin 2017: Patrick Gunia - Migration of a realtime stats prod...Flink Forward Berlin 2017: Patrick Gunia - Migration of a realtime stats prod...
Flink Forward Berlin 2017: Patrick Gunia - Migration of a realtime stats prod...
 
Event and signal driven programming
Event and signal driven programmingEvent and signal driven programming
Event and signal driven programming
 
The Ring programming language version 1.2 book - Part 51 of 84
The Ring programming language version 1.2 book - Part 51 of 84The Ring programming language version 1.2 book - Part 51 of 84
The Ring programming language version 1.2 book - Part 51 of 84
 
Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012
 
VC++ Fundamentals
VC++ FundamentalsVC++ Fundamentals
VC++ Fundamentals
 
Flink Forward Berlin 2017: Zohar Mizrahi - Python Streaming API
Flink Forward Berlin 2017: Zohar Mizrahi - Python Streaming APIFlink Forward Berlin 2017: Zohar Mizrahi - Python Streaming API
Flink Forward Berlin 2017: Zohar Mizrahi - Python Streaming API
 
Understanding JavaScript Event-based Interactions
Understanding JavaScript Event-based InteractionsUnderstanding JavaScript Event-based Interactions
Understanding JavaScript Event-based Interactions
 
Dynamic languages for .NET CLR
Dynamic languages for .NET CLRDynamic languages for .NET CLR
Dynamic languages for .NET CLR
 
MLOps Case Studies: Building fast, scalable, and high-accuracy ML systems at ...
MLOps Case Studies: Building fast, scalable, and high-accuracy ML systems at ...MLOps Case Studies: Building fast, scalable, and high-accuracy ML systems at ...
MLOps Case Studies: Building fast, scalable, and high-accuracy ML systems at ...
 
The Ring programming language version 1.5.1 book - Part 67 of 180
The Ring programming language version 1.5.1 book - Part 67 of 180The Ring programming language version 1.5.1 book - Part 67 of 180
The Ring programming language version 1.5.1 book - Part 67 of 180
 
Nexmark with beam
Nexmark with beamNexmark with beam
Nexmark with beam
 
Brief Introduction to Cython
Brief Introduction to CythonBrief Introduction to Cython
Brief Introduction to Cython
 
Pharos
PharosPharos
Pharos
 
Delegateless Coordinator
Delegateless CoordinatorDelegateless Coordinator
Delegateless Coordinator
 
Meteor Boulder meetup #1
Meteor Boulder meetup #1Meteor Boulder meetup #1
Meteor Boulder meetup #1
 
Logux, a new approach to client-server communication by Andrey Sitnik
Logux, a new approach to client-server communication by Andrey SitnikLogux, a new approach to client-server communication by Andrey Sitnik
Logux, a new approach to client-server communication by Andrey Sitnik
 

Plus de Open-IT

Microsoft kinect
Microsoft kinectMicrosoft kinect
Microsoft kinect
Open-IT
 
Сам себе АНБ, API социальных сетей
Сам себе АНБ, API социальных сетейСам себе АНБ, API социальных сетей
Сам себе АНБ, API социальных сетей
Open-IT
 
Talkbits service architecture and deployment
Talkbits service architecture and deploymentTalkbits service architecture and deployment
Talkbits service architecture and deployment
Open-IT
 

Plus de Open-IT (13)

Mathematical optimization and python
Mathematical optimization and pythonMathematical optimization and python
Mathematical optimization and python
 
Секретный доклад
Секретный докладСекретный доклад
Секретный доклад
 
Rust: абстракции и безопасность, совершенно бесплатно
Rust: абстракции и безопасность, совершенно бесплатноRust: абстракции и безопасность, совершенно бесплатно
Rust: абстракции и безопасность, совершенно бесплатно
 
Введение в Apache Cassandra
Введение в Apache CassandraВведение в Apache Cassandra
Введение в Apache Cassandra
 
λ | Lenses
λ | Lensesλ | Lenses
λ | Lenses
 
Cooking Cassandra
Cooking CassandraCooking Cassandra
Cooking Cassandra
 
Командная разработка “толстых клиентов”
Командная разработка “толстых клиентов”Командная разработка “толстых клиентов”
Командная разработка “толстых клиентов”
 
Akka и реактивное программирование на JVM
Akka и реактивное программирование на JVMAkka и реактивное программирование на JVM
Akka и реактивное программирование на JVM
 
Fuel's current use cases, architecture and next steps
Fuel's current use cases, architecture and next stepsFuel's current use cases, architecture and next steps
Fuel's current use cases, architecture and next steps
 
Виртуализация как инструмент разработчика
Виртуализация как инструмент разработчикаВиртуализация как инструмент разработчика
Виртуализация как инструмент разработчика
 
Microsoft kinect
Microsoft kinectMicrosoft kinect
Microsoft kinect
 
Сам себе АНБ, API социальных сетей
Сам себе АНБ, API социальных сетейСам себе АНБ, API социальных сетей
Сам себе АНБ, API социальных сетей
 
Talkbits service architecture and deployment
Talkbits service architecture and deploymentTalkbits service architecture and deployment
Talkbits service architecture and deployment
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

How to make friends python with win32 api