paulenot
@paulenot
IT Issue

Почему не выполняется условие if в python3?

Этот скрипт проверяет, есть ли подключение к домену, функция работает, чтение и запись в файл тоже работает, но не могу понять, почему пропускается условие if (check(item) == 1) понять не могу почему он тупо перезаписывает массив не проверив ответ функции check(), мало того, он стирает последний символ на последнем домене и создает пустую строку..

Исходный код:
#!/usr/bin/env python3
import requests
import sys

def check(url):
	domain = 'http://' + url
	try:
		response = requests.get(domain, verify=False, timeout=(1, 1))
		print('[ ЗАНЯТ ] ' + domain)
		return 0
	except requests.ConnectionError:
		print('[ СВОБОДЕН ] ' + domain)
		return 1


def opens(filename):
	in_list = []
	with open(filename, 'r') as filehandle:
		for line in filehandle:
			currentPlace = line[:-1]
			in_list.append(currentPlace)

	return in_list


places = opens(sys.argv[1])
out_places = 'out_' + sys.argv[1]
for item in places:
	if (check(item) == 1):
		with open(out_places, 'w') as filehandle:
			for listitem in places:
				filehandle.write('%s\n' % listitem)


Я сравнил вывод этого скрипта с выводом сервиса https://www.cy-pr.com/tools/masswhois/
Из 8 проверенных доменов скрипт правильно определил 6...
[ ЗАНЯТ ] http://ac-web.ru - Правильно
[ СВОБОДЕН ] http://cn-web.ru - Правильно
[ СВОБОДЕН ] http://jp-web.ru - Правильно
[ СВОБОДЕН ] http://uk-web.ru - Правильно
[ СВОБОДЕН ] http://ad-web.ru - Ошибка
[ СВОБОДЕН ] http://adm-web.ru - Ошибка
[ СВОБОДЕН ] http://br-web.ru - Правильно
[ ЗАНЯТ ] http://adv-web.ru - Правильно


Уже крыша немного едет, так же есть проблема, при проверке домена, не получив ответа(пробовал зайти, бесконечно грузит) он выбивает ошибку:
[ ЗАНЯТ ] http://ac-web.ru
[ СВОБОДЕН ] http://cn-web.ru
[ СВОБОДЕН ] http://jp-web.ru
[ СВОБОДЕН ] http://uk-web.ru
[ СВОБОДЕН ] http://ad-web.ru
[ СВОБОДЕН ] http://adm-web.ru
[ СВОБОДЕН ] http://br-web.ru
[ ЗАНЯТ ] http://adv-web.ru
/home/usr/.local/lib/python3.6/site-packages/urllib3/connectionpool.py:1004: InsecureRequestWarning: Unverified HTTPS request is being made to host 'aero-web.ru'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning,
Traceback (most recent call last):
  File "/home/usr/.local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 421, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "/home/usr/.local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 416, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/lib/python3.6/http/client.py", line 1356, in getresponse
    response.begin()
  File "/usr/lib/python3.6/http/client.py", line 307, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.6/http/client.py", line 268, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.6/socket.py", line 586, in readinto
    return self._sock.recv_into(b)
  File "/usr/lib/python3.6/ssl.py", line 1012, in recv_into
    return self.read(nbytes, buffer)
  File "/usr/lib/python3.6/ssl.py", line 874, in read
    return self._sslobj.read(len, buffer)
  File "/usr/lib/python3.6/ssl.py", line 631, in read
    v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/usr/.local/lib/python3.6/site-packages/requests/adapters.py", line 449, in send
    timeout=timeout
  File "/home/usr/.local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 720, in urlopen
    method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
  File "/home/usr/.local/lib/python3.6/site-packages/urllib3/util/retry.py", line 400, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/home/usr/.local/lib/python3.6/site-packages/urllib3/packages/six.py", line 735, in reraise
    raise value
  File "/home/usr/.local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 672, in urlopen
    chunked=chunked,
  File "/home/usr/.local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 423, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  File "/home/usr/.local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 331, in _raise_timeout
    self, url, "Read timed out. (read timeout=%s)" % timeout_value
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='aero-web.ru', port=443): Read timed out. (read timeout=1)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./requester.py", line 29, in <module>
    if (check(item) == 1):
  File "./requester.py", line 8, in check
    response = requests.get(domain, verify=False, timeout=(5, 1))
  File "/home/usr/.local/lib/python3.6/site-packages/requests/api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "/home/usr/.local/lib/python3.6/site-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/home/usr/.local/lib/python3.6/site-packages/requests/sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/usr/.local/lib/python3.6/site-packages/requests/sessions.py", line 665, in send
    history = [resp for resp in gen] if allow_redirects else []
  File "/home/usr/.local/lib/python3.6/site-packages/requests/sessions.py", line 665, in <listcomp>
    history = [resp for resp in gen] if allow_redirects else []
  File "/home/usr/.local/lib/python3.6/site-packages/requests/sessions.py", line 245, in resolve_redirects
    **adapter_kwargs
  File "/home/usr/.local/lib/python3.6/site-packages/requests/sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "/home/usr/.local/lib/python3.6/site-packages/requests/adapters.py", line 529, in send
    raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='aero-web.ru', port=443): Read timed out. (read timeout=1)


Помогите пожалуйста отладить код, что бы он правильно сохранял вывод и не прерывался на первых строках списка.. Заранее благодарю!
  • Вопрос задан
  • 730 просмотров
Решения вопроса 1
@PavelMos
Посмотреть, какие выдаются исключения :

http://ac-web.ru[ ЗАНЯТ ]
http://cn-web.ru 
 [ Exception HTTPConnectionPool(host='cn-web.ru', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001F9A57FDE80>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)) ]
http://jp-web.ru 
 [ Exception HTTPConnectionPool(host='jp-web.ru', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001F9A581F080>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)) ]
http://uk-web.ru 
 [ Exception HTTPConnectionPool(host='uk-web.ru', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001F9A581F0B8>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)) ]
<b>http://ad-web.ru </b>
 [ Exception HTTPConnectionPool(host='ad-web.ru', port=80): Max retries exceeded with url: / (Caused by <b>ConnectTimeoutError(</b><urllib3.connection.HTTPConnection object at 0x000001F9A58230F0>, 'Connection to ad-web.ru timed out. (connect timeout=1)')) ]
http://adm-web.ru[ ЗАНЯТ ]
http://br-web.ru 
 [ Exception HTTPConnectionPool(host='br-web.ru', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001F9A58234A8>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)) ]
http://adv-web.ru[ ЗАНЯТ ]
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы