2018年6月7日木曜日

開発環境

入門 Python 3 (Bill Lubanovic (著)、斎藤 康毅 (監修)、長尾 高弘 (翻訳)、オライリージャパン)の11章(並行処理とネットワーク)、11.3(復習問題)3.を取り組んでみる。

コード(Emacs)

Python 3

server3.py

#!/usr/bin/env python3
import datetime
from xmlrpc.server import SimpleXMLRPCServer

f = open('server3.txt', 'w')

print('11-3', file=f)


def func(s):
    print(s, file=f)
    if s == 'time':
        return datetime.datetime.now().isoformat()
    return 'xxxxx'


host = 'localhost'
port = 6789
server = SimpleXMLRPCServer((host, port), logRequests=False)
server.register_function(func, 'func')
server.serve_forever()

client3.py

#!/usr/bin/env python3
import datetime
import time
from xmlrpc.client import ServerProxy

print('11-3')

host = '127.0.0.1'
port = 6789
proxy = ServerProxy(f'http://{host}:{port}/')

for i in range(10):
    if i % 2 == 0:
        s = proxy.func('time')
    else:
        s = proxy.func('TIME')
    print(s)
    time.sleep(5)

入出力結果(Terminal, Jupyter(IPython))

$ ./server3.py &
[1] 67809
$ ./client3.py
11-3
2018-06-07T16:34:02.932685
xxxxx
2018-06-07T16:34:12.940363
xxxxx
2018-06-07T16:34:22.945094
xxxxx
2018-06-07T16:34:32.949924
xxxxx
2018-06-07T16:34:42.957024
xxxxx
$ fg
./server3.py
  C-c C-cTraceback (most recent call last):
  File "./server3.py", line 21, in <module>
    server.serve_forever()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 236, in serve_forever
    ready = selector.select(poll_interval)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/selectors.py", line 323, in select
    r, w, _ = self._select(self._readers, self._writers, [], timeout)
KeyboardInterrupt
$ cat server3.txt 
11-3
time
TIME
time
TIME
time
TIME
time
TIME
time
TIME
$ 

0 コメント:

コメントを投稿

関連コンテンツ