import winreg
winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\\Uninstall\{F57F0CBD-3260-4021-83E6-CA2224672634$}', 0, (winreg.KEY_WOW64_64KEY + winreg.KEY_READ))
import pytest
@pytest.fixture()
def fixture1():
print "Fixture 1"
@pytest.fixture()
def fixture2():
print "Fixture 2"
import pytest
def skip_non_matching_url(option):
return pytest.mark.skipif(
not getattr(pytest.config.option, option, None),
reason="Url doesn't match command line option"
)
@skip_non_matching_url("url2")
def test_my_url2(fixture2):
print "Test my url2"
@skip_non_matching_url("url1")
def test_my_url1(fixture1):
print "Test my ulr1"
$ python -m pytest -vs --url1 ya.ru
collected 2 items
test_something.py::test_my_url2 SKIPPED
test_something.py::test_my_url1 Fixture 1
Test my ulr1
PASSED
$ python -m pytest -vs --url2 ya.ru
collected 2 items
test_something.py::test_my_url2 Fixture 2
Test my url2
PASSED
test_something.py::test_my_url1 SKIPPED
import pytest
@pytest.mark.url2
def test_my_url2(fixture2):
print "Test my url2"
@pytest.mark.url1
def test_my_url1(fixture1):
print "Test my ulr1"
$ python -m pytest -vs -m url2
collected 2 items
test_something.py::test_my_url2 Fixture 2
Test my url2
PASSED
$ python -m pytest -vs -m url1
collected 2 items
test_something.py::test_my_url1 Fixture 1
Test my ulr1
PASSED
''.isalpha() # False
' '.isalpha() # False
'!@#'.isalpha() # False
'abc'.isalpha() # True
'123'.isalpha() # False
'abc123'.isalpha() # False
'абв'.isalpha() # True
'абв123'.isalpha() # False
def my_comb(pattern, r):
comb_list = combinations(pattern, r)
for c in comb_list:
yield ''.join(x if x in c else '-' for x in pattern)
>>> list(my_comb('ABC', 2))
['AB-', 'A-C', '-BC']
>>> list(my_comb('ABCDE', 3))
['ABC--', 'AB-D-', 'AB--E', 'A-CD-', 'A-C-E', 'A--DE', '-BCD-', '-BC-E', '-B-DE', '--CDE']
>>> import lxml.etree
>>> doc = """
... <?xml version="1.0" encoding="ANSI" ?>
... <data>
... <items>
... <item name="item1">1</item>
... <item name="item2">2</item>
... <item name="item3">3</item>
... <item name="item4">4</item>
... </items>
... </data>
... .----------------------------------------------------------
... """
>>> parser = lxml.etree.XMLParser(recover=True)
>>> tree = lxml.etree.fromstring(doc, parser)
>>> [element.text for element in tree.iter('item')]
['1', '2', '3', '4']
>>> import xml.etree.ElementTree as ET
>>> doc = """
... <?xml version="1.0" encoding="ANSI" ?>
... <data>
... <items>
... <item name="item1">1</item>
... <item name="item2">2</item>
... <item name="item3">3</item>
... <item name="item4">4</item>
... </items>
... </data>
... .----------------------------------------------------------
... """
>>> tree = ET.fromstring(doc.strip('\n-.'))
>>> [element.text for element in tree.iter('item')]
['1', '2', '3', '4']
>>> from email.header import decode_header
>>> s = '=?UTF-8?B?0KHQsdC10YDQsdCw0L3QuiDQntC90LvQsNC50L0uINCe0LTQvdC+0YDQsNC3?='
>>> bytes, encoding = decode_header(s)[0]
>>> bytes.decode(encoding)
'Сбербанк Онлайн. Однораз'
from collections import defaultdict
s = {'Которая часто': 6, 'чулане хранится': 7, 'Который построил': 8, 'Который бранится': 2, 'хвоста Который': 4}
def sum_update(d):
updated = defaultdict(int)
for k, v in d.items():
updated[k.split()[0]] += v
return dict(updated)
sum_update(s)
# {'Которая': 6, 'Который': 10, 'хвоста': 4, 'чулане': 7}
from collections import Counter
def sum_update(d):
updated = Counter()
for k, v in d.items():
updated[k.split()[0]] += v
return dict(updated)
def quadratic_eq_formatter(nums):
num_f = {1: '{:+.0f}', 0: '{:+.1f}'}
eq = '{}x^2{}x{}=0'.format(*(num_f[x.is_integer()] for x in nums))
return eq.format(*nums) if nums[0] < 0 else eq.format(*nums)[1:]
nums = (a, b, c)
print(quadratic_eq_formatter(nums))
print(quadratic_eq_formatter([-3.0, -2.7, 7.0]))
'-3x^2-2.7x+7=0'
print(quadratic_eq_formatter([2.0, 5.0, -4.0]))
'2x^2+5x-4=0'
print(quadratic_eq_formatter([-2.1, -4.5, 8.3]))
'-2.1x^2-4.5x+8.3=0'
eq = '{}x^2{}x{}=0'.format(*(num_f[x.is_integer()] for x in nums))
eq = '{}x\u00B2{}x{}=0'.format(*(num_f[x.is_integer()] for x in nums))
print(quadratic_eq_formatter([-2.0, 5.0, 5.2]))
-2x²+5x+5.2=0
In [1]: class A:
...: def sayHello(self):
...: print('Hello!')
...:
In [2]: def sayHello(self):
...: print('Hey')
...:
In [3]: a = A()
In [4]: b = A()
In [5]: a.sayHello()
Hello!
In [6]: a.sayHello = sayHello.__get__(a)
In [7]: a.sayHello()
Hey
In [8]: b.sayHello()
Hello!
>>> def heyfunc():
... print('hey')
...
>>> def supfunc():
... print('sup')
...
>>> funcdict = {'heyfunc': heyfunc, 'supfunc': supfunc}
>>> f_name = input()
hey
>>> next_func = funcdict.get(f_name+'func')
>>> next_func
<..function heyfunc at 0x10926d268..>
>>> next_func()
hey
card_funcs = {}
def register_cf(card_func):
'''register card function'''
card_funcs[card_func.__name__] = card_func
return card_func
@register_cf
def card_func1():
print('Running card1')
@register_cf
def card_func2():
print('Running card2')
@register_cf
def card_func3():
print('Running card3')
if __name__ == '__main__':
print('running funcs from registry:')
for fn, fobj in card_funcs.items():
print(fn, '->', fobj)
fobj()
-----
running funcs from registry:
card_func3 -> <..function card_func3 at 0x1069ae9d8..>
Running card3
card_func2 -> <..function card_func2 at 0x1071ea9d8..>
Running card2
card_func1 -> <..function card_func1 at 0x10db190d0..>
Running card1
>>> import re
>>> keywords = ['ИД безопасности:', 'Тип входа:', 'Дата:', 'Код события:']
>>> pattern = re.compile(r'\s+\w+|'.join(keywords))
>>> with open('log.txt', encoding='utf-8' ) as f:
... for line in f:
... if pattern.search(line):
... print(line)
...
Дата: 04.07.2017 13:04:31
Код события: 4624
ИД безопасности: система
Тип входа: 7
ИД безопасности: rootpc\root
returncode = subprocess.run(['sh', 'команда, которую я выполняю'], stdout=subprocess.PIPE).returncode
print(returncode)
>>> ints = [random.randint(-10,10) for x in range(1,101)]
>>> while ints:
... print('{0:>5}{1:>5}{2:>5}{3:>5}'.format(*ints[:4]))
... ints = ints[4:]
...
5 5 6 -2
-4 6 0 4
9 -7 6 5
-1 0 2 10
7 -8 8 1
7 4 -7 6
-5 -6 -3 9
2 -4 2 2
-1 9 -7 -2
5 10 4 10
-9 8 5 7
7 9 -5 -7
9 10 10 9
0 -8 -4 -3
-5 5 6 -10
1 -6 -4 -9
-2 5 -4 2
10 10 9 -6
-1 -3 -3 -1
2 6 -5 -7
-5 1 7 -3
3 9 -8 -7
10 5 -5 6
2 9 -1 -4
-1 -2 -9 -2
from prettytable import PrettyTable # Импортируем установленный модуль.
# Определяем твою шапку и данные.
th = [...]
td = [...]
columns = len(th) # Подсчитаем кол-во столбцов на будущее.
table = PrettyTable(th) # Определяем таблицу.
# Cкопируем список td, на случай если он будет использоваться в коде дальше.
td_data = td[:]
# Входим в цикл который заполняет нашу таблицу.
# Цикл будет выполняться до тех пор пока у нас не кончатся данные
# для заполнения строк таблицы (список td_data).
while td_data:
# Используя срез добавляем первые пять элементов в строку.
# (columns = 5).
table.add_row(td_data[:columns])
# Используя срез переопределяем td_data так, чтобы он
# больше не содержал первых 5 элементов.
td_data = td_data[columns:]
print(table) # Печатаем таблицу
+-------------------+---------------+------+-------------+------------+
| MAC Address | IP Address | Mode | Rate (Mbps) | Signal (%) |
+-------------------+---------------+------+-------------+------------+
| 11:11:11:11:11:11 | 192.168.0.103 | 11n | 65 | 100 |
| 11:11:11:11:11:11 | 192.168.0.103 | 11n | 65 | 100 |
| 11:11:11:11:11:11 | 192.168.0.103 | 11n | 65 | 100 |
| 11:11:11:11:11:11 | 192.168.0.103 | 11n | 65 | 100 |
| 11:11:11:11:11:11 | 192.168.0.103 | 11n | 65 | 100 |
+-------------------+---------------+------+-------------+------------+
import requests
import bs4
tut = []
names = []
r = requests.get('https://vk.com/uporols_you').text
soup = bs4.BeautifulSoup(r, 'lxml')
im = soup.find_all('img', class_='ph_img')
for a in im:
s = a.get('data-src_big').split('|')[0]
tut.append(s)
for num, link in enumerate(tut):
p = requests.get(link)
out = open("img%s.jpg" % (num), 'wb')
out.write(p.content)
out.close()
for t, a in tut, names:
for i in ('a', 'b', 'c', 'd'):
for x in ('1', '2', '3', '4'):
print(i + " => " + x)