macOS 10.12
Я пытаюсь упаковать скрипт Python (называемый getUrls_douyu.py
) как отдельное приложение / исполняемый файл без зависимостей, поэтому я использую py2app. Проблема в том, что когда я пытаюсь запустить свое приложение после сборки (из терминала с: open getUrls_douyu.app
), ничего не происходит, и я получаю следующее сообщение об ошибке:
Ошибка консоли:
Detected missing constraints for <private>. It cannot be placed because there are not enough constraints to fully define the size and origin. Add the missing constraints, or set translatesAutoresizingMaskIntoConstraints=YES and constraints will be generated for you. If this view is laid out manually on macOS 10.12 and later, you may choose to not call [super layout] from your override. Set a breakpoint on DETECTED_MISSING_CONSTRAINTS to debug. This error will only be logged once.
Если я попытаюсь open getUrls_douyu.app/Contents/MacOS/getUrls_douyu
(исполняемый файл внутри пакета приложения), я получу другую ошибку:
IOError: Could not find a suitable TLS CA certificate bundle, invalid path: /Users/<REDACTED>/getUrls_douyu/dist/getUrls_douyu.app/Contents/Resources/lib/python2.7/site-packages.zip/certifi/cacert.pem
Но я проверил, и cacert.pem там действительно существует, так что сертификат по какой-то причине недействителен? Мой скрипт .py использует модуль requests
для получения информации с веб-страницы, которая, я думаю, должна быть проблемой. Вот мой полный скрипт на python:
import requests
from bs4 import BeautifulSoup
html = requests.get('https://www.douyu.com/directory/all').text
soup = BeautifulSoup(html, 'html.parser')
urls = soup.select('.play-list-link')
output = '';
output += '[' #open json array
for i, url in enumerate(urls):
channelName = str(i);
channelUrl = 'http://douyu.com' + url.get('href')
output += '{'
output += '\"channelName\":' + '\"' + channelName.encode('utf-8') + '\",'
output += '\"channelUrl\":' + '\"' + channelUrl.encode('utf-8') + '\"'
output += '},'
output = output[:-1]
output += ']'
print output
Когда я впервые создал этот скрипт, я сделал это в virtualenv, в котором я выполнил pip install requests
и pip install beautifulsoup4
, и проверил, что скрипт успешно работает без проблем.
Этот ответ на вопрос касательно ошибки cacert.pem с модулем запросов мне не помог. Вот мой скрипт на python при применении данного решения:
import requests
from bs4 import BeautifulSoup
import sys, os
def override_where():
""" overrides certifi.core.where to return actual location of cacert.pem"""
# change this to match the location of cacert.pem
return os.path.abspath("cacert.pem")
# is the program compiled?
if hasattr(sys, "frozen"):
import certifi.core
os.environ["REQUESTS_CA_BUNDLE"] = override_where()
certifi.core.where = override_where
# delay importing until after where() has been replaced
import requests.utils
import requests.adapters
# replace these variables in case these modules were
# imported before we replaced certifi.core.where
requests.utils.DEFAULT_CA_BUNDLE_PATH = override_where()
requests.adapters.DEFAULT_CA_BUNDLE_PATH = override_where()
html = requests.get('https://www.douyu.com/directory/all').text
soup = BeautifulSoup(html, 'html.parser')
urls = soup.select('.play-list-link')
output = '';
output += '[' #open json array
for i, url in enumerate(urls):
channelName = str(i);
channelUrl = 'http://douyu.com' + url.get('href')
output += '{'
output += '\"channelName\":' + '\"' + channelName.encode('utf-8') + '\",'
output += '\"channelUrl\":' + '\"' + channelUrl.encode('utf-8') + '\"'
output += '},'
output = output[:-1]
output += ']'
print output
Мне кажется, я правильно настроил файл py2app setup.py ...
from setuptools import setup
APP = ['getUrls_douyu.py']
DATA_FILES = []
OPTIONS = {}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
Извините за подробный вопрос! Я новичок в Python, так что я думаю, что сделал глупую ошибку. Любая помощь с благодарностью.