コンテンツへスキップ

testinfra サンプル

$ more test_service2.py
import pytest

@pytest.mark.parametrize("name,version", [
    ("httpd","2.2.5"),
    ("python", "2.9"),
])

def test_packages(host, name, version):
    pkg = host.package(name)
    assert pkg.is_installed
    assert pkg.version.startsith(version)

@pytest.mark.parametrize("name", [
    ("httpd"),
    ("chronyd"),
])
def test_service(host, name):
    service = host.service(name)
    assert service.is_running

実行結果

$ py.test -v ./test_service2.py
/usr/local/lib/python3.6/site-packages/testinfra-6.0.0-py3.6.egg/_testinfra_renamed.py:10: DeprecationWarning: testinfra package has been renamed to pytest-testinfra. Please `pip install pytest-testinfra` and `pip uninstall testinfra` and update your package requirements to avoid this message
============================================================================= test session starts =============================================================================
platform linux -- Python 3.6.8, pytest-6.2.4, py-1.10.0, pluggy-1.0.0.dev0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /home/user1
plugins: testinfra-6.0.0, testinfra-6.3.0
collected 4 items

test_service2.py::test_packages[local-httpd-2.2.5] PASSED                                                                                                               [ 25%]
test_service2.py::test_packages[local-python-2.9] PASSED                                                                                                                [ 50%]
test_service2.py::test_service[local-httpd] PASSED                                                                                                                      [ 75%]
test_service2.py::test_service[local-chronyd] PASSED                                                                                                                    [100%]

============================================================================== 4 passed in 0.68s ==============================================================================

 

server.yml

hostname: server1

network: 
- eno1: 
  device: eno1  
  ipaddress: 192.168.1.1
  netmask: 255.255.255.0
  gateway: 192.168.1.254
- eno2:
  device: eno2 
  ipaddress: 192.168.1.2
  netmask: 255.255.255.0
  gateway: 192.168.1.254

 

読み込み

>>> with open('E:\\my-document\\Programing\\testinfra\\servers\\server1.yaml','r') as yml:
...     config = yaml.safe_load(yml)
... 
>>> config
{'hostname': 'server1', 'network': [{'eno1': None, 'device': 'eno1', 'ipaddress': '192.168.1.1', 'netmask': '255.255.255.0', 'gateway': '192.168.1.254'}, {'eno2': None, 'device': 'eno2', 'ipaddress': '192.168.1.2', 'netmask': '255.255.255.0', 'gateway': '192.168.1.254'}]}
>>> config['hostname']
'server1'
>>> config['network']
[{'eno1': None, 'device': 'eno1', 'ipaddress': '192.168.1.1', 'netmask': '255.255.255.0', 'gateway': '192.168.1.254'}, {'eno2': None, 'device': 'eno2', 'ipaddress': '192.168.1.2', 'netmask': '255.255.255.0', 'gateway': '192.168.1.254'}]
>>> config['network'][0]
{'eno1': None, 'device': 'eno1', 'ipaddress': '192.168.1.1', 'netmask': '255.255.255.0', 'gateway': '192.168.1.254'}
>>> config['network'][0]['ipaddress']
'192.168.1.1'
>>> config['network'][1]['ipaddress'] 
'192.168.1.2'
>>>

 

ファイルの読み込み

# -*- coding:utf-8 -*-
import codecs

FILE="テキストファイル"
f=codecs.open(FILE,'rb','utf-8','')
contents=f.read()
f.close()
for line in contents.split('\n'):
    print(line)

ファイルへ出力

# -*- coding:utf-8 -*-
import codecs

FILE="test.txt"
f=codecs.open(FILE,'wb','utf-8')
f.write("書き込みテスト")
f.close()

 

バージョンは2でも3でも同じ。
どちらもモジュールreを使う。

>>> import re
>>> string = 'here is some text I wrote .'

その1

>>> re.sub( '\s+', ' ',string ).strip()
'here is some text I wrote .'

その2

>>> ' '.join(string.split())
'here is some text I wrote .'

Python 3.5.5で動作確認済み

■ 使い方
henkan.py [置換前文字列] [置換後文字列] [Inputファイル名] [Outputファイル名(省略した場合は画面出力を行う)]

■ コード

#!/usr/bin/python
import os,sys

n = len(sys.argv)

if not 3 <= n <= 5:
        print("引数が不足しています。")
else:
        stext = sys.argv[1]
        rtext = sys.argv[2]
        input_file = sys.stdin
        output_file = sys.stdout
        if n > 3:
                input_file = open(sys.argv[3])
        if n > 4:
                output_file = open(sys.argv[4], 'w')
        for s in input_file:
                output_file.write(s.replace(stext, rtext))
        output_file.close()
        input_file.close()

import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
type(wb)

wb.get_sheet_names()
sheet=wb.get_sheet_by_name('sheet3')
sheet
sheet.title
another_sheet = wb.active
another_sheet

# シートからセルを取得する。
sheet['A1']
sheet['A1'].value
c = sheet['b1']
c.value

sheet.cell(row=1, column=2).value
for i in range(1, 8, 2):
    print(i, sheet.cell(row=i, column=2).value)

■ディレクトリ構造
~/www/index.html
~/www/cgi-bin/input.py
※input.pyには実行権を与える

■Webサーバの起動
cd ~/www
python3 -m http.server --cgi 8000

■ソースコード index.html

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>test</title>
    </head>
    <body>
        <h1>テスト</h1>
        <form action="cgi-bin/input.py" method="post">
            <p><label>テキスト入力:<input type="text" name="mytext" size="20"></label></p>
            <p><input type="submit" value="送信"></p>
        </form>
    </body>
</html>

input.py 実行権を与える。

#!/usr/bin/python
# -*- coding: utf-8 -*-
import cgi
import sys
import io

html_body = """
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>受信したデータを表示</title>
    </head>
    <body>
        <h1>%s</h1>
    </body>
</html>
"""

form = cgi.FieldStorage()
s = form.getvalue('mytext', '')

if s == "a":
    print(html_body % "aです")
else:
    print(html_body % "aではないです")