- 安裝 Visual Studio IntelliCode
- 設定VS Code 的 IntelliSense Engine
搜尋方塊,輸入:Python Intelli
選取:Vsintellicode > Python : Completions Enabled
取消:Python : Jedi Enabled
根據提示訊息Reload language engine - 使用VS IntelliCode 當 IntelliSense Engine的妙用:
Jedi無法正常解析,類別內self所延伸的屬性、方法、控制項名稱,控制項所可使用屬性、方法...,但改用VS IntelliCode後,可以暢快地享受IntelliSense的大大好處。
站內搜尋:Yahoo搜尋的結果,如果沒有給完整的網址,請在站內再搜尋一次!
2019-08-24
VS Code : 用Visual Studio IntelliCode取代 Jedi 來當 IntelliSense engine
2019-08-23
VS Code : 讓pylint 除了錯誤(error)以外,排除顯示(disabled)不影響程式執行的警告(warning)、提示訊息(infomation)的訊息
Pylint的警告(warning)、提示訊息(infomation)等訊息,通常不會影響程式的正常執行,但通常會讓程式碼看起來很不舒服,這些訊息可能包含:
- Missing class docstring pylint(missing-docstring)
- Found indentation with tabs instead of spaces pylint(mixed-indentation)
- Variable name "e1" doesn't conform to snake_case naming style pylint(invalid-name)
- No space allowed after bracket pylint(bad-whitespace)
- Method could be a function pylint(no-self-use)
- Trailing whitespace pylint(trailing-whitespace)
- Constant name "win" doesn't conform to UPPER_CASE naming style pylint(invalid-name)
- ...
VS Code : pylint 出現錯誤訊息:No name 'QApplication' in module 'PyQt5.QtWidgets',解決方法
- 錯誤訊息:No name 'QApplication' in module 'PyQt5.QtWidgets'
- 訊息內容:
{
"resource": "/d:/MyWorkSpaces/VSWorks/ch04/qt04_lineEdit04.py",
"owner": "python",
"code": "no-name-in-module",
"severity": 8,
"message": "No name 'QApplication' in module 'PyQt5.QtWidgets'",
"source": "pylint",
"startLineNumber": 5,
"startColumn": 1,
"endLineNumber": 5,
"endColumn": 1
}
- 錯誤原因:
跟所使用的Pylint有關,所採用的版本預設不支援外部擴充模組(Extenions),PyQt5是C++所寫的外部擴充(Extension)。 - 解決方法:
2019-08-21
Python : 使用PyInstaller把專案程式打包封裝成EXE執行檔
- 安裝PyInstaller:
(base) C:\ProgramData\Anaconda3>pip install PyInstaller
Collecting PyInstaller
Downloading https://files.pythonhosted.org/packages/e2/c9/0b44b2ea87ba36395483a672fddd07e6a9cb2b8d3c4a28d7ae76c7e7e1e5/PyInstaller-3.5.tar.gz (3.5MB)
|████████████████████████████████| 3.5MB 3.3MB/s
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing wheel metadata ... done
Collecting pywin32-ctypes>=0.2.0 (from PyInstaller)
Downloading https://files.pythonhosted.org/packages/9e/4b/3ab2720f1fa4b4bc924ef1932b842edf10007e4547ea8157b0b9fc78599a/pywin32_ctypes-0.2.0-py2.py3-none-any.whl
Collecting pefile>=2017.8.1 (from PyInstaller)
Downloading https://files.pythonhosted.org/packages/36/58/acf7f35859d541985f0a6ea3c34baaefbfaee23642cf11e85fe36453ae77/pefile-2019.4.18.tar.gz (62kB)
|████████████████████████████████| 71kB 2.3MB/s
Requirement already satisfied: setuptools in c:\programdata\anaconda3\lib\site-packages (from PyInstaller) (41.0.1)
Collecting altgraph (from PyInstaller)
Downloading https://files.pythonhosted.org/packages/0a/cc/646187eac4b797069e2e6b736f14cdef85dbe405c9bfc7803ef36e4f62ef/altgraph-0.16.1-py2.py3-none-any.whl
Requirement already satisfied: future in c:\programdata\anaconda3\lib\site-packages (from pefile>=2017.8.1->PyInstaller) (0.17.1)
Building wheels for collected packages: PyInstaller
Building wheel for PyInstaller (PEP 517) ... done
Stored in directory: C:\Users\Hannibal\AppData\Local\pip\Cache\wheels\c6\a4\e0\d9a1c5d3d876eb0675171281c293aed80839115e2eb022e6d2
Successfully built PyInstaller
Building wheels for collected packages: pefile
Building wheel for pefile (setup.py) ... done
Stored in directory: C:\Users\Hannibal\AppData\Local\pip\Cache\wheels\1c\a1\95\4f33011a0c013c872fe6f0f364dc463a2588120820e40a30d8
Successfully built pefile
Installing collected packages: pywin32-ctypes, pefile, altgraph, PyInstaller
Successfully installed PyInstaller-3.5 altgraph-0.16.1 pefile-2019.4.18 pywin32-ctypes-0.2.0
- PyInstaller的參數:
(base) C:\ProgramData\Anaconda3\Scripts>PyInstaller --help
usage: pyinstaller [-h] [-v] [-D] [-F] [--specpath DIR] [-n NAME]
[--add-data <SRC;DEST or SRC:DEST>]
[--add-binary <SRC;DEST or SRC:DEST>] [-p DIR]
[--hidden-import MODULENAME]
[--additional-hooks-dir HOOKSPATH]
[--runtime-hook RUNTIME_HOOKS] [--exclude-module EXCLUDES]
[--key KEY] [-d {all,imports,bootloader,noarchive}] [-s]
[--noupx] [--upx-exclude FILE] [-c] [-w]
[-i <FILE.ico or FILE.exe,ID or FILE.icns>]
[--version-file FILE] [-m <FILE or XML>] [-r RESOURCE]
[--uac-admin] [--uac-uiaccess] [--win-private-assemblies]
[--win-no-prefer-redirects]
[--osx-bundle-identifier BUNDLE_IDENTIFIER]
[--runtime-tmpdir PATH] [--bootloader-ignore-signals]
[--distpath DIR] [--workpath WORKPATH] [-y]
[--upx-dir UPX_DIR] [-a] [--clean] [--log-level LEVEL]
scriptname [scriptname ...]
positional arguments:
scriptname name of scriptfiles to be processed or exactly one
.spec-file. If a .spec-file is specified, most options
are unnecessary and are ignored.
optional arguments:
-h, --help show this help message and exit
-v, --version Show program version info and exit.
--distpath DIR Where to put the bundled app (default: .\dist)
--workpath WORKPATH Where to put all the temporary work files, .log, .pyz
and etc. (default: .\build)
-y, --noconfirm Replace output directory (default:
SPECPATH\dist\SPECNAME) without asking for confirmation
--upx-dir UPX_DIR Path to UPX utility (default: search the execution path)
-a, --ascii Do not include unicode encoding support (default:included if available)
--clean Clean PyInstaller cache and remove temporary files before building.
--log-level LEVEL Amount of detail in build-time console messages. LEVEL
may be one of TRACE, DEBUG, INFO, WARN, ERROR,
CRITICAL (default: INFO).
What to generate:
-D, --onedir Create a one-folder bundle containing an executable (default)
-F, --onefile Create a one-file bundled executable.
--specpath DIR Folder to store the generated spec file (default: current directory)
-n NAME, --name NAME Name to assign to the bundled app and spec file
(default: first script's basename)
What to bundle, where to search:
--add-data <SRC;DEST or SRC:DEST>
Additional non-binary files or folders to be added to
the executable. The path separator is platform
specific, ``os.pathsep`` (which is ``;`` on Windows
and ``:`` on most unix systems) is used. This option
can be used multiple times.
--add-binary <SRC;DEST or SRC:DEST>
Additional binary files to be added to the executable.
See the ``--add-data`` option for more details. This
option can be used multiple times.
-p DIR, --paths DIR A path to search for imports (like using PYTHONPATH).
Multiple paths are allowed, separated by ';', or use
this option multiple times
--hidden-import MODULENAME, --hiddenimport MODULENAME
Name an import not visible in the code of the
script(s). This option can be used multiple times.
--additional-hooks-dir HOOKSPATH
An additional path to search for hooks. This option
can be used multiple times.
--runtime-hook RUNTIME_HOOKS
Path to a custom runtime hook file. A runtime hook is
code that is bundled with the executable and is
executed before any other code or module to set up
special features of the runtime environment. This
option can be used multiple times.
--exclude-module EXCLUDES
Optional module or package (the Python name, not the
path name) that will be ignored (as though it was not
found). This option can be used multiple times.
--key KEY The key used to encrypt Python bytecode.
How to generate:
-d {all,imports,bootloader,noarchive}, --debug {all,imports,bootloader,noarchive}
Provide assistance with debugging a frozen
application. This argument may be provided multiple
times to select several of the following options.
- all: All three of the following options.
- imports: specify the -v option to the underlying
Python interpreter, causing it to print a message
each time a module is initialized, showing the
place (filename or built-in module) from which it
is loaded. See
https://docs.python.org/3/using/cmdline.html#id4.
- bootloader: tell the bootloader to issue progress
messages while initializing and starting the
bundled app. Used to diagnose problems with
missing imports.
- noarchive: instead of storing all frozen Python
source files as an archive inside the resulting
executable, store them as files in the resulting
output directory.
-s, --strip Apply a symbol-table strip to the executable and
shared libs (not recommended for Windows)
--noupx Do not use UPX even if it is available (works
differently between Windows and *nix)
--upx-exclude FILE Prevent a binary from being compressed when using upx.
This is typically used if upx corrupts certain
binaries during compression. FILE is the filename of
the binary without path. This option can be used
multiple times.
Windows and Mac OS X specific options:
-c, --console, --nowindowed
Open a console window for standard i/o (default). On
Windows this option will have no effect if the first
script is a '.pyw' file.
-w, --windowed, --noconsole
Windows and Mac OS X: do not provide a console window
for standard i/o. On Mac OS X this also triggers
building an OS X .app bundle. On Windows this option
will be set if the first script is a '.pyw' file. This
option is ignored in *NIX systems.
-i <FILE.ico or FILE.exe,ID or FILE.icns>, --icon <FILE.ico or FILE.exe,ID or FILE.icns>
FILE.ico: apply that icon to a Windows executable.
FILE.exe,ID, extract the icon with ID from an exe.
FILE.icns: apply the icon to the .app bundle on Mac OS X
Windows specific options:
--version-file FILE add a version resource from FILE to the exe
-m <FILE or XML>, --manifest <FILE or XML>
add manifest FILE or XML to the exe
-r RESOURCE, --resource RESOURCE
Add or update a resource to a Windows executable. The
RESOURCE is one to four items,
FILE[,TYPE[,NAME[,LANGUAGE]]]. FILE can be a data file
or an exe/dll. For data files, at least TYPE and NAME
must be specified. LANGUAGE defaults to 0 or may be
specified as wildcard * to update all resources of the
given TYPE and NAME. For exe/dll files, all resources
from FILE will be added/updated to the final
executable if TYPE, NAME and LANGUAGE are omitted or
specified as wildcard *.This option can be used
multiple times.
--uac-admin Using this option creates a Manifest which will
request elevation upon application restart.
--uac-uiaccess Using this option allows an elevated application to
work with Remote Desktop.
Windows Side-by-side Assembly searching options (advanced):
--win-private-assemblies
Any Shared Assemblies bundled into the application
will be changed into Private Assemblies. This means
the exact versions of these assemblies will always be
used, and any newer versions installed on user
machines at the system level will be ignored.
--win-no-prefer-redirects
While searching for Shared or Private Assemblies to
bundle into the application, PyInstaller will prefer
not to follow policies that redirect to newer
versions, and will try to bundle the exact versions of
the assembly.
Mac OS X specific options:
--osx-bundle-identifier BUNDLE_IDENTIFIER
Mac OS X .app bundle identifier is used as the default
unique program name for code signing purposes. The
usual form is a hierarchical name in reverse DNS
notation. For example:
com.mycompany.department.appname (default: first
script's basename)
Rarely used special options:
--runtime-tmpdir PATH
Where to extract libraries and support files in
`onefile`-mode. If this option is given, the
bootloader will ignore any temp-folder location
defined by the run-time OS. The ``_MEIxxxxxx``-folder
will be created here. Please use this option only if
you know what you are doing.
--bootloader-ignore-signals
Tell the bootloader to ignore signals rather than
forwarding them to the child process. Useful in
situations where e.g. a supervisor process signals
both the bootloader and child (e.g. via a process
group) to avoid signalling the child twice. - 打包封裝的範例
PyInstaller -F -w --key "TheKeyUsedToEncryptPythonBytecode" CallWeatherWin.py
-F:打包封裝成一個執行檔 (-D:打包封裝成一個目錄)
-w:這是一個視窗程式(window),不是主控台程式(console)
--key:程式碼封裝加密的金鑰
打包封裝的結果放在dist目錄內。打包的執行檔只能在原相同作業系統下執行(64位元/32位元是有區分的)
D:\MyWorkSpaces\VSWorks\ch10a\weather2>PyInstaller -F -w --key "TheKeyUsedToEncryptPythonBytecode" CallWeatherWin.py
159 INFO: PyInstaller: 3.5
164 INFO: Python: 3.7.3
167 INFO: Platform: Windows-10-10.0.18362-SP0
179 INFO: wrote D:\MyWorkSpaces\VSWorks\ch10a\weather2\CallWeatherWin.spec
181 INFO: UPX is not available.
212 INFO: Extending PYTHONPATH with paths
['D:\\MyWorkSpaces\\VSWorks\\ch10a\\weather2',
'D:\\MyWorkSpaces\\VSWorks\\ch10a\\weather2']
212 INFO: Will encrypt Python bytecode with key: TheKeyUsedToEncr
221 INFO: Adding dependencies on pyi_crypto.py module
223 INFO: checking Analysis
223 INFO: Building Analysis because Analysis-00.toc is non existent
224 INFO: Initializing module dependency graph...
236 INFO: Initializing module graph hooks...
251 INFO: Analyzing base_library.zip ...
13714 INFO: Analyzing hidden import 'Crypto.Cipher._AES'
14066 INFO: running Analysis Analysis-00.toc
14107 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
required by c:\programdata\anaconda3\python.exe
14779 INFO: Caching module hooks...
14811 INFO: Analyzing D:\MyWorkSpaces\VSWorks\ch10a\weather2\CallWeatherWin.py
16113 INFO: Processing pre-safe import module hook urllib3.packages.six.moves
20871 INFO: Processing pre-safe import module hook six.moves
25919 INFO: Loading module hooks...
25920 INFO: Loading module hook "hook-certifi.py"...
25927 INFO: Loading module hook "hook-Crypto.py"...
Traceback (most recent call last):
File "", line 2, in
ModuleNotFoundError: No module named 'Crypto.Math'
26049 INFO: Loading module hook "hook-cryptography.py"...
26814 INFO: Loading module hook "hook-encodings.py"...
26983 INFO: Loading module hook "hook-pydoc.py"...
26987 INFO: Loading module hook "hook-PyQt5.py"...
27509 INFO: Loading module hook "hook-PyQt5.QtCore.py"...
27678 INFO: Loading module hook "hook-PyQt5.QtGui.py"...
28090 INFO: Loading module hook "hook-PyQt5.QtWidgets.py"...
28761 INFO: Loading module hook "hook-xml.py"...
29119 INFO: Looking for ctypes DLLs
29157 INFO: Analyzing run-time hooks ...
29165 INFO: Including run-time hook 'pyi_rth_certifi.py'
29177 INFO: Including run-time hook 'pyi_rth_pyqt5.py'
29202 INFO: Looking for dynamic libraries
32584 INFO: Looking for eggs
32585 INFO: Using Python library c:\programdata\anaconda3\python37.dll
32586 INFO: Found binding redirects:
[]
32606 INFO: Warnings written to D:\MyWorkSpaces\VSWorks\ch10a\weather2\build\CallWeatherWin\warn-CallWeatherWin.txt
32762 INFO: Graph cross-reference written to D:\MyWorkSpaces\VSWorks\ch10a\weather2\build\CallWeatherWin\xref-CallWeatherWin.html
32848 INFO: checking PYZ
32848 INFO: Building PYZ because PYZ-00.toc is non existent
32850 INFO: Building PYZ (ZlibArchive) D:\MyWorkSpaces\VSWorks\ch10a\weather2\build\CallWeatherWin\PYZ-00.pyz
34987 INFO: Building PYZ (ZlibArchive) D:\MyWorkSpaces\VSWorks\ch10a\weather2\build\CallWeatherWin\PYZ-00.pyz completed successfully.
35048 INFO: checking PKG
35050 INFO: Building PKG because PKG-00.toc is non existent
35050 INFO: Building PKG (CArchive) PKG-00.pkg
35731 WARNING: One binary added with two internal names.
35732 WARNING: ('libGLESv2.dll',
'C:\\programdata\\anaconda3\\lib\\site-packages\\PyQt5\\Qt\\bin\\libGLESv2.dll',
'BINARY')
35733 WARNING: was placed previously at
35735 WARNING: ('PyQt5\\Qt\\bin\\libGLESv2.dll',
'C:\\programdata\\anaconda3\\lib\\site-packages\\PyQt5\\Qt\\bin\\libGLESv2.dll',
'BINARY')
60664 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
60689 INFO: Bootloader c:\programdata\anaconda3\lib\site-packages\PyInstaller\bootloader\Windows-64bit\runw.exe
60690 INFO: checking EXE
60691 INFO: Building EXE because EXE-00.toc is non existent
60693 INFO: Building EXE from EXE-00.toc
60696 INFO: Appending archive to EXE D:\MyWorkSpaces\VSWorks\ch10a\weather2\dist\CallWeatherWin.exe
61113 INFO: Building EXE from EXE-00.toc completed successfully.
2019-08-17
讓在Anaconda Navigator環境下安裝執行的Visual Studio Code增加PYQT Integration的擴充功能
- 在Visual Studio Code安裝PYQT Integration的擴充功能
- 安裝PYQT Integration擴充功能後,將會增加下列功能,或更多,例如:
從VS code直接開啟 designer.exe 新增 ui form,在VS Code下預覽 ui form ...
PYQT: New Form Open designer PYQT: Edit In Designer Open designer with current ui form PYQT: Preview Preview current ui form PYQT: Compile Form Compile ui form to path defined in "pyqt-integration.pyuic.compile.filepath" PYQT: Compile Resource Compile qrc file to path defined in "pyqt-integration.pyrcc.compile.filepath" PYQT: Generate Translation File (.ts) Compile UI file (.py) to translation file with path defined in "pyqt-integration.pylupdate.compile.filepath"
Compile .pro filePYQT: Open With Qt Linguist Open with Qt Linguist for translation file (.ts) - 如果從 VS Code,無法正常啟動 designer.exe 或 pyuic5 ...,可以透過擴充延伸模組設定,指定正確的路徑、檔名 ...
- 以Qtdesigner這個設定項目為例,designer.exe,通常都是放在,Anaconda3安裝目錄的\Lib\site-packages\pyqt5_tools\路徑下。
- 設定項目的參考資料:
pyqt-integration.qtdesigner.path Path of executable file of qt designer, the extension will ask you to set at the first time it runs, e.g. c:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python35\\Lib\\site-packages\\pyqt5-tools\\designer.exe pyqt-integration.pyuic.cmd "pyuic" command, default "pyuic5" pyqt-integration.pyuic.compile.filepath Compile file path, relative path as default, switch to absolute path by involving ${workspace}, e.g. ${workspace}\\UI\\Ui_${ui_name}.py pyqt-integration.pyuic.compile.addOptions Additional options for pyuic compiling, it can be a combination of '-x', '-d', '-i', etc. pyqt-integration.pyrcc.cmd "pyrcc" command, default "pyrcc5" pyqt-integration.pyrcc.compile.filepath Compile file path, relative path as default, switch to absolute path by involving ${workspace}, e.g. ${workspace}\\QRC\\${qrc_name}_rc.py pyqt-integration.pyrcc.compile.addOptions Additional options for pyrcc compiling, it can be a combination of '-root', '-threshold', '-compress', '-no-compress', etc. pyqt-integration.pylupdate.cmd "pylupdate" command, default "pylupdate5" pyqt-integration.pylupdate.compile.filepath Only works when compiling an UI file (.py), Stores the target '.ts' file's path, relative path as default, switch to absolute path by involving ${workspace}, e.g. ${workspace}\\TS\\${ts_name}.ts pyqt-integration.pylupdate.compile.addOptions Additional options for pylupdate, it can be a combination of '-verbose', '-noobsolete', '-tr-function', '-translate-function', etc. pyqt-integration.linguist.cmd "linguist" command, default "linguist"
讓在Anaconda Navigator環境下安裝的 Visual Studio Code (VS code),以繁體中文的介面顯示
安裝Visual Studio Code (VS Code) 繁體中文語言包(Chinese (Traditional) Language Pack for Visual Studio Code)的步驟:
- 點擊「Extensions」→在Extensions marketplace的搜尋方塊內輸入:chinese language pack,選取「Chinese (Traditional) Language Pack for Visual Studio Code」,可以查看VS Code 的中文(繁體)語言套件的說明擊使用方式。
- 點擊「Install」,安裝後會提示:重新開啟VS Code
- 重新啟動後,就會以繁體中文的語言界面顯示。如果沒有以中文顯示,可以參考以下的使用方式說明:
安裝了之後,在 locale.json 裡面設定 "locale": "zh-tw" 即可載入中文(繁體)的語言套件。要修改locale.json,可以按下Ctrl+Shift+P來呼叫 命令選擇區,輸入 "config" 以從其他可用命令裡面篩選出 Configure Language 命令。
2019-08-15
Python 3 : SQLite3的存取基本步驟,及異常錯誤處理 (try ... except ... )
- 參考資料:
- https://docs.python.org/3/library/sqlite3.html
- https://docs.python.org/zh-cn/3/library/sqlite3.html
- http://doc.codingdict.com/python_352/library/sqlite3.html
- 詳解Python 資料庫的Connection、Cursor兩大物件
- 在Python 3 環境下,使用SQLilte3,對資料庫操作的基本步驟(一般原則):
- 用sqlite3.connect("資料庫檔名.副檔名") 建立資料庫連線,並將這個連線物件指定給一個連線物件變數,例如:oConn=sqlite3.connect("資料庫檔名.副檔名")
- 建立連線物件的cursor物件,例如:cTest=oConn.cursor()
- 執行SQL命令,將結果以tuple資料組存放在cursor物件內。例如:cTest.execute("SQL命令")
- 取得目標資料集,例如:oTest=cTest.fetchall()
- 處理取得的資料集,例如:for aTest in oTest :
- 關閉資料庫連線,例如:oConn.close()
- 對於不需要return回傳執行結果的資料庫操作,可以簡化操作步驟,如下:
- 建立資料庫連線,例如:oConn=sqlite3.connect("資料庫檔名.副檔名")
- 執行SQL命令,例如:oConn.execute("SQL命令")
- 更新資料庫,例如:oConn.commite()
- cursor物件是一個指標物件,cursor物件執行SQL命令後,會將結果存放在cursor物件內,並可透過fetchone, fetchmany, fetchall ... 等方法或函數來操作cursor物件內的資料。
一個資料庫連線的使用過程,可以根據目的需求的不同,建立多個cursor物件來使用,不同名稱的cursor物件,如果不再使用可給予關閉close()。同一個cursor物件,可以透過不同的命令執行,賦予不同的資料內容。
使用VS code 可以快速瀏覽sqlite3 cursor可以使用的方法、屬性...
- 可以使用 VS Code,查看Python 有哪些處理 SQLite 錯誤例外異常的類別,例如;Error, DatabaseErrot, DataError, ProgrammingError ...,在不分開測試錯誤類別來源的情況下,可以使用預設的異常錯誤例外處理 Exception ...
import sqlite3
oConn=sqlite3.connect("test.db")
zSQL="UPDATE T SET T2='5',T3='8' WHERE T1='1' "
try:
oConn.execute(zSQL)
except sqlite3.DataError as d:
print("d=",d)
except sqlite3.DatabaseError as de:
print("de=",de)
except sqlite3.Error as e:
print("e=",e)
except Exception as ex:
print("ex=",ex)
oConn.commit()
#de= database is locked
- 適度地在SQLite的CRUD操作上使用try ... except ...,可以確保程式持續執行,或在執行過程排除異常、錯誤...。
2019-08-13
Python 3 : 使用 urllib.request.retrieve 下載檔案
import datetime as dt
import urllib.request
zToday=dt.datetime.now().strftime('%Y%m%d')
##上市公司基本資料
zUrlToRetrieve="http://mopsfin.twse.com.tw/opendata/t187ap03_L.csv"
zSaveFileAtPath=".\\t187ap03_L_%s.csv"%(zToday)
urllib.request.urlretrieve(url=zUrlToRetrieve, filename=zSaveFileAtPath)
##上櫃公司基本資料
zUrlToRetrieve="http://mopsfin.twse.com.tw/opendata/t187ap03_O.csv"
zSaveFileAtPath=".\\t187ap03_O_%s.csv"%(zToday)
urllib.request.urlretrieve(zUrlToRetrieve, zSaveFileAtPath)
##下載後,遇有存檔相同檔名的檔案,會覆蓋較舊的檔案
import urllib.request
zToday=dt.datetime.now().strftime('%Y%m%d')
##上市公司基本資料
zUrlToRetrieve="http://mopsfin.twse.com.tw/opendata/t187ap03_L.csv"
zSaveFileAtPath=".\\t187ap03_L_%s.csv"%(zToday)
urllib.request.urlretrieve(url=zUrlToRetrieve, filename=zSaveFileAtPath)
##上櫃公司基本資料
zUrlToRetrieve="http://mopsfin.twse.com.tw/opendata/t187ap03_O.csv"
zSaveFileAtPath=".\\t187ap03_O_%s.csv"%(zToday)
urllib.request.urlretrieve(zUrlToRetrieve, zSaveFileAtPath)
##下載後,遇有存檔相同檔名的檔案,會覆蓋較舊的檔案
Python 3 : urllib.request 存取網頁的內建標準模組 (URL handling modules) / urllib.error try ... except ... else 異常錯誤處理
- 官方參考文件:
- urllib包含處理網路請求和操作URL的五個子模組:
- urllib.error : 包含由urllib.request所丟出的異常、錯誤
- urllib.parse : 解析URL
- urllib.request : 開啟及讀取URL的內容
- urllib.response :
- urllib.robotparse : 用來解析robots.txt
- urllib.request模組,網頁內容請求及回應內容讀取的程式碼範例:zTimeStamp=str(dt.datetime.now().timestamp()*1000)[:13]
zURLtoGetStockInfo="https://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=%s&json=1&delay=0&_=%s"
zURLtoGetStockInfo=zURLtoGetStockInfo%('tse_1440.tw',zTimeStamp)
##(1)建立請求並開啟網頁
oResp=urllib.request.urlopen(zURLtoGetStockInfo)
##(2)取得網頁回應的內容
oHTML=oResp.read()
##(3)從網頁回應內容中載入JSON內容
oJSON=json.loads(oHTML)
print(oJSON)
##等同上面(1)請求、(2)回應、(3)載入三段程序
oJSON=json.loads(urllib.request.urlopen(zURLtoGetStockInfo).read())
print(oJSON)
- 利用try ... except ... 取得讀取網頁內容失敗的訊息:
try:
oJSON=json.loads(urllib.request.urlopen(zURLtoGetStockInfo).read())
print(oJSON)
#except Exception as e:
#urllib.error.URLError : 有reason,無code
#except urllib.error.URLError as e:
#urllib.error.HTTPError : 有code,reason,headers
except urllib.error.HTTPError as e:
print("ErrorCode=", e.code)
print("ErrorReason=", e.reason)
print("ErrorDescription=", e)
oJSON={'rtcode':'error404'}
if oJSON['rtcode']=='error404':
print("請求網頁內容失敗或發生錯誤!!!")
else:
print("請求網頁內容成功!!!")
# ErrorCode= 404
# ErrorReason= Not Found
# ErrorDescription= HTTP Error 404: Not Found
# 請求網頁內容失敗或發生錯誤!!!
2019-08-11
SQLite3 : 欄位串接的運算子是 || (double pipe)
2019-08-10
使用Python 處理 SQLite3 跨資料庫檔案間的資料表資料複製
- 作法:
建立兩個connection,分別對應來源及目標資料庫檔案
一次讀取來源的所有資料,再逐筆寫入目標資料表內 - 程式碼:
import sqlite3
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
##來源資料庫
dbName="LineNotifierStock-20190731.db3"
oConnSource=sqlite3.connect(dbName)
##目標資料庫
dbName="StockNotifier.db3"
oConnTarget=sqlite3.connect(dbName)
##作法:一次讀取來源的所有資料,再逐筆寫入目標資料表內
zSQL="Select * from StdToNote
oConnSource.row_factory = dict_factory
cSource=oConnSource.cursor()
cSource.execute(zSQL)
oSource=cSource.fetchall()
print(oSource)
for aSource in oSource :
zSQL="""INSERT INTO StdToNote
(stockID,stockName,doNoteOpen,doNoteRate,
doNotePrice,doNoteAccVol,doNoteUpDown,noteType,
refPrice,rateHigh,rateLow,priceHigh,priceLow,memo)
values('%s','%s','%s','%s','%s','%s','%s','%s',%f,%f,%f,%f,%f,'%s')
"""
zSQL=zSQL%(aSource['stockID'],aSource['stockName'],aSource['isNoteOpen'], \
aSource['isNoteRate'],aSource['isNotePrice'],aSource['isNoteAccVol'],
aSource['isNoteUpDown'],aSource['noteType'],aSource['refPrice'], \
aSource['rateHigh'],aSource['rateLow'],aSource['priceHigh'], \
aSource['priceLow'],aSource['memo'])
oConnTarget.execute(zSQL)
oConnTarget.commit()
oConnSource.close()
oConnTarget.close()
print("Data Copied Ready!!!")
- 查看執行結果:
從政府資料開放平台(open data),取得上市上櫃公司基本資料(CSV),使用Python將資料寫入SQLite3資料庫
- 政府資料開放平台 ( https://data.gov.tw/ )
- 上市公司基本資料(18419) - https://data.gov.tw/dataset/18419
- 上櫃股票基本資料(25036) - https://data.gov.tw/dataset/25036
- 實際資料提供者:證交所的公開資訊觀測站 https://mopsfin.twse.com.tw/
- 資料格式只提供 CSV ,更新頻率→每日
- 取得資料的連結點:
- http://mopsfin.twse.com.tw/opendata/t187ap03_L.csv
- http://mopsfin.twse.com.tw/opendata/t187ap03_O.csv
- 程式碼:
## Table : Stocks (stockType,stockID,stockAbbr,industryType,releaseDate)
## stockType : tse->上市,otc->上櫃
## 上市公司基本資料(18419) - 政府資料開放平台 https://data.gov.tw/dataset/18419
## 上櫃股票基本資料(25036) - 政府資料開放平台 https://data.gov.tw/dataset/25036
## 主要欄位說明:
## 出表日期[0]、公司代號[1]、公司名稱[2]、公司簡稱[3]、外國企業註冊地國[4]、產業別[5]、住址、
## 營利事業統一編號、董事長、總經理、發言人、發言人職稱、代理發言人、總機電話、成立日期、上市日期、
## 普通股每股面額、實收資本額、私募股數、特別股、編制財務報表類型、股票過戶機構、過戶電話、過戶地址、
## 簽證會計師事務所、簽證會計師1、簽證會計師2、英文簡稱、英文通訊地址、傳真機號碼、電子郵件信箱、網址
zSQL="""CREATE TABLE IF NOT EXISTS `Stocks` (
`stockType` VARCHAR(4) NOT NULL,
`stockID` VARCHAR(8) NOT NULL,
`stockAbbr` VARCHAR(30) NOT NULL,
`industryType` VARCHAR(30),
`releaseDate` VARCHAR(12),
PRIMARY KEY (`stockID`)
);
"""
oConn.execute(zSQL)
oConn.commit()
zSQL="SELECT * FROM Stocks "
cStocks=oConn.execute(zSQL)
rStock=cStocks.fetchone()
if rStock==None:
##寫入上市公司資料
zCsvUrl="http://mopsfin.twse.com.tw/opendata/t187ap03_L.csv"
oHTML=requests.get(zCsvUrl)
oHTML.encoding='utf-8'
oList=oHTML.text.split('\r\n')
for i in range(1,len(oList)-1):
aList=oList[i].replace('"','').split(',')
zSQL="INSERT INTO Stocks (stockType,stockID,stockAbbr,industryType,releaseDate) values ('tse','%s','%s','%s','%s'); "
zSQL=zSQL%(aList[1],aList[3],aList[5],aList[0])
oConn.execute(zSQL)
oConn.commit()
##寫入上櫃公司資料
zCsvUrl="http://mopsfin.twse.com.tw/opendata/t187ap03_O.csv"
oHTML=requests.get(zCsvUrl)
oHTML.encoding='utf-8'
oList=oHTML.text.split('\r\n')
for i in range(1,len(oList)-1):
aList=oList[i].replace('"','').split(',')
zSQL="INSERT INTO Stocks (stockType,stockID,stockAbbr,industryType,releaseDate) values ('otc','%s','%s','%s','%s'); "
zSQL=zSQL%(aList[1],aList[3],aList[5],aList[0])
oConn.execute(zSQL)
oConn.commit()
- 透過Python寫入的資料:
2019-08-06
Python : 日期時間的計算運算
- 匯入日期時間模組,以指定的方式,建立日期時間物件
- # 匯入 datetime 模組,並以 mDT 作為 datetime 的別名
import datetime as mDT
# 使用 mDT 模組,建立一個現在的日期時間(datetime)物件 oNow
oNow=mDT.datetime.now()
# 指定 年 月 日 時 分 秒,建立日期時間物件
oTheDateTime=mDT.datetime(year=2019,month=8,day=8,hour=17,minute=30,second=0)
print(oTheDateTime.strftime('%Y-%m-%d %H:%M:%S'))
# >>>2019-08-08 17:30:00
oTheDateTime2=mDT.datetime(2018,1,23,8,15,20)
print(oTheDateTime2.strftime('%Y-%m-%d %H:%M:%S'))
# >>>2018-01-23 08:15:20 - 透過 timedelta(...) 進行日期時間的加減計算
oAddOneDay=mDT.timedelta(days=+1)
oTheDateTime=oTheDateTime+oAddOneDa
print(oTheDateTime.strftime('%Y-%m-%d %H:%M:%S'))
# >>>2019-08-09 17:30:00
oAdd21Days=mDT.timedelta(weeks=2,days=6,hours=23,minutes=50,seconds=600)
# 以上合計剛好 21天
oTheDateTime2=oTheDateTime2-oAdd21Days+oAddOneDay
print(oTheDateTime2.strftime('%Y-%m-%d %H:%M:%S'))
# >>>2018-01-03 08:15:20
# 23日 - 21天 + 1天 = 3日 - timedelta 可以用時間單位:週、天、時、分、秒,當計算的單位,但不可以用 年、月。
# oAfter2Months=mDT.timedelta(months=2)
# >>>TypeError: 'months' is an invalid keyword argument for __new__()
# oAfter2Years=mDT.timedelta(years=2)
# >>>TypeError: 'years' is an invalid keyword argument for __new__() - 參考資料:
https://docs.python.org/3.7/library/datetime.html?highlight=datetime%20format#datetime.date.__format__
Python : 日期時間的格式化輸出
- 匯入 datetime 模組,建立今天的日期時間物件
多多利用 Visual Studio Code的 intellisense (intellicode) 的功能,可以藉提示的功能,多認識一些模組內的class(類別)、方法、屬性。
- 格式化輸出 今天(現在)的日期時間內容
# 匯入 datetime 模組,並以 mDT 作為 datetime 的別名
import datetime as mDT
# 使用 mDT 模組,建立一個今天的日期時間(datetime)物件 oToday
oToday=mDT.datetime.today()
print(oToday.strftime('%Y-%m-%d %H:%M:%S.%f'))
# >>>2019-08-06 14:27:59.485471
- 格式化輸出的代碼、說明、及對應輸出範例:
代碼輸出說明輸出範例 %a
Weekday as locale’s abbreviated name. Sun, Mon, …, Sat (en_US);So, Mo, …, Sa (de_DE)%A
Weekday as locale’s full name. Sunday, Monday, …, Saturday (en_US);Sonntag, Montag, …, Samstag (de_DE)%w
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 0, 1, …, 6 %d
Day of the month as a zero-padded decimal number. 01, 02, …, 31 %b
Month as locale’s abbreviated name. Jan, Feb, …, Dec (en_US);Jan, Feb, …, Dez (de_DE)%B
Month as locale’s full name. January, February, …, December (en_US);Januar, Februar, …, Dezember (de_DE)%m
Month as a zero-padded decimal number. 01, 02, …, 12 %y
Year without century as a zero-padded decimal number. 00, 01, …, 99 %Y
Year with century as a decimal number. 0001, 0002, …, 2013, 2014, …, 9998, 9999 %H
Hour (24-hour clock) as a zero-padded decimal number. 00, 01, …, 23 %I
Hour (12-hour clock) as a zero-padded decimal number. 01, 02, …, 12 %p
Locale’s equivalent of either AM or PM. AM, PM (en_US);am, pm (de_DE)%M
Minute as a zero-padded decimal number. 00, 01, …, 59 %S
Second as a zero-padded decimal number. 00, 01, …, 59 %f
Microsecond as a decimal number, zero-padded on the left. 000000, 000001, …, 999999 %z
UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive). (empty), +0000, -0400, +1030, +063415, -030712.345216 %Z
Time zone name (empty string if the object is naive). (empty), UTC, EST, CST %j
Day of the year as a zero-padded decimal number. 001, 002, …, 366 %U
Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. 00, 01, …, 53 %W
Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. 00, 01, …, 53 %c
Locale’s appropriate date and time representation. Tue Aug 16 21:30:00 1988 (en_US);Di 16 Aug 21:30:00 1988 (de_DE)%x
Locale’s appropriate date representation. 08/16/88 (None);08/16/1988 (en_US);16.08.1988 (de_DE)%X
Locale’s appropriate time representation. 21:30:00 (en_US);21:30:00 (de_DE)%%
A literal '%'
character.%
- 參考資料:
https://docs.python.org/3.7/library/datetime.html?highlight=datetime%20format#datetime.date.__format__
2019-08-05
Python : 字串串接的方法
import datetime as dt
zName='Huang'
zNow3=dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
nPrice=15
nQty=24
zPrint=''
zHi='Hi!!! '
zNow=', it is '
##字串直接相加串接
zPrint=zPrint+zHi+zName+zNow+zNow3
print(zPrint) #Hi!!! Huang, it is 2019-08-05 21:00:16.658
#使用join()串接串列中的字串
zPrint=''
aString=['Hi!!! ','Huang',', it is ','2019-08-05 21:00:16.658']
zPrint=zPrint.join(aString)
print(zPrint) #Hi!!! Huang, it is 2019-08-05 21:00:16.658
#使用%格式化字串帶入變數
zPrint="Hi!!! %s, it is %s. %dx%d=%d"
zPrint=zPrint%(zName, zNow3, nPrice, nQty, nPrice*nQty)
print(zPrint) #Hi!!! Huang, it is 2019-08-05 21:00:16.658. 15x24=360
SQL : INSERT INTO ... SELECT ... WHERE NOT EXISTS ( SELECT ...) 。如果資料不存在就插入一筆資料表。
目標:如果查詢的資料不存在,就插入一筆資料。
想法:如果按照CREATE TABLE IF NOT EXISTS的思考方式,會想要使用 IF NOT EXISTS的作法,以SELECT查詢資料作為條件判斷,可以用 WHERE NOT EXISTS的作法。當然還有其他的方法可以達到需求。
SQL參考語法:
INSERT INTO Config (cfgID, cfgDesc, srhTLD, srhNUM, srhSTOP, srhPAUSE, memo)
SELECT '0000','Inserted by program','com',5,5,120,''
WHERE NOT EXIST ( SELECT 1 FROM Config WHERE cfgID='0000' )
用SQLiteStudio查詢執行結果:
想法:如果按照CREATE TABLE IF NOT EXISTS的思考方式,會想要使用 IF NOT EXISTS的作法,以SELECT查詢資料作為條件判斷,可以用 WHERE NOT EXISTS的作法。當然還有其他的方法可以達到需求。
SQL參考語法:
INSERT INTO Config (cfgID, cfgDesc, srhTLD, srhNUM, srhSTOP, srhPAUSE, memo)
SELECT '0000','Inserted by program','com',5,5,120,''
WHERE NOT EXIST ( SELECT 1 FROM Config WHERE cfgID='0000' )
用SQLiteStudio查詢執行結果:
SQL / SQLite3 : CREATE TABLE IF NOT EXISTS 。如果資料表不存在就新增建立這個資料表。
目標:如果資料表不存在就新增建立這個資料表。
SQL參考語法:
SQL參考語法:
在SQLite,也可以使用VARCHAR
CREATE TABLE IF NOT EXISTS `Config` (
`cfgID` VARCHAR(04) DEFAULT('0000') NOT NULL,
`cfgDesc` VARCHAR(50) NOT NULL,
`...` ....,
PRIMARY KEY(`cfgID`)
);
2019-08-04
安裝 PyCharm 2019.02 for Windows with Anaconda Plugin
- 取得PyCharm各種版本的網址:
https://www.jetbrains.com/pycharm/download/other.html
Professional / Community 兩種授權、Linux / Windows / macOS 三種平台、一般 / with Anaconda plugin 兩種安裝方式,共有12個安裝檔可供選擇。 - PyCharm區分為兩種授權版本,功能上網站寫得很清楚:
- Professional : Free trial。For both Scientific and Web Python development. With HTML, JS, and SQL support.
- Community : Free, open-source。For pure Python development
- 這裡要安裝的是Windows with Anaconda plugin。在安裝的過程除了會出現是否要安奘miniconnda外(因為已安裝Anaconda,所以就沒有選擇安裝miniconda),並不會出現Anaconda的安裝相關選項。
但要建立專案時,就會有Anaconda的相關選項。 - 建立新專案:
- 選擇專案的所在位置
- 可以選擇透過已安裝的Anaconda,重新建立一個新的虛擬環境
- 也可以選擇透過已安裝的Anaconda,選取已存在的環境或虛擬環境
再分別輸入選取:Conda Environment / Virtualenv Environment / System Interpreter / Pipenv Environment - 專案建立OK,新增一個Python程式碼,開始Coding ...
- 使用conda指令操作虛擬環境
- 建立虛擬環境:
conda create -n 虛擬環境名稱 python=版本 anaconda - 切換至其他虛擬環境
activate 虛擬環境名稱 - 切換回base環境
deactivate - 複製目前所在的(虛擬)環境
conda create -n 虛擬環境名稱 --clone root - 查看所有的(虛擬)環境
conda info -e - 移除虛擬環境
conda remove -n 虛擬環境名稱 --all - Package模組安裝移除的指令:
- 安裝:
pip install 模組名稱==版本編號 - 移除:
pip uninstall 模組名稱
在Google Chrome加入擴充功能 Vimeo Video Downloader,使用Chrome就可以下載vimeo影片
- 先用Google Search的功能,找到快速連結 vimeo video downloader 的連結位置:
https://www.google.com.tw/search?q=chrome+vimeo
https://chrome.google.com/webstore/detail/vimeo-video-downloader/cgpbghdbejagejmciefmekcklikpoeel - 點擊『加到Chrome』(當然要有安裝Chrome),如果有開啟vimeo網頁,就記得重新開一下Chrome吧!
- 就像下圖,影片的右上的下方,會多出一個下載的工具按鈕
- Enjoy the Vimeo vedios!!!
2019-08-03
VNC解決中文輸入切換問題的作法:被控端(server)有realVNC, tightVNC
我目前的工作環境,透過VNC連線操作的電腦,主要有:
- RaspBerry Pi 3 Model B+,作業系統:2019-06-20-raspbian-buster-full.img
使用系統預設安裝realVNC server - win10,安裝 tightVNC server
- win10,realVNC viewer / tightVNC viewer
連線作法:
- realVNC viewer 連 realVNC server → OK
- tightVNC viewer 連 tightVNC server → OK。但是中英文切換時,按個shift鍵 或 ctrl+space鍵,總是遠端的win 10 作業系統和近端的win 10作業系統,兩端都產生作用,最慘的是:當近端是中文輸入模式,遠端就不能輸入了,困擾極了...
- tightVNC viewer 連 realVNC server → not OK,因為tightVNC不支援加解密傳輸。
- realVNC viewer 連 tightVNC server,OK。效果好,還有統一管理遠端連接點的功能,更重要的是中文輸入的困擾不見了....
集中管理連接的遠端,還提供管理連線屬性的介面:
- 結論:不管是realVNV server 還是 tightVNC server,我目前通通選擇使用realVNC viewer連線。
2019-08-02
在Anaconda3環境下安裝eric6 (The Eric Python IDE, v19.7),spyder也可以繼續正常使用
安裝Eric6 v19.7 前的環境:
安裝過程,說明如下:
- Anaconda3 -2019.07 ( https://www.anaconda.com/distribution/#windows )
- 已在Anaconda3環境下使用的Applications:Spyder(v3.3.6), Jupyter Notebook(v6.0.0), Visual Studio Code(v1.36.1)。已安裝QtPy模組(v1.8.0)(QtPy provides support for PyQt5, PyQt4, PySide2 and PySide using the Qt5 layout (where the QtGui module has been split into QtGui and QtWidgets). https://pypi.org/project/QtPy/ )
- Thonny (v3.1.2)。已安裝 pyqt5-tools模組(這個模組對pyqt5的版本需求是5.11.3)
安裝過程,說明如下:
- 就按照Eric6網站上的安裝說明,取得最新版本
https://sourceforge.net/projects/eric-ide/files/eric6/stable/19.07/eric6-19.7.zip/download - 將zip解壓縮至:Anaconda3安裝路徑下的以下位置:
C:\ProgramData\Anaconda3\Lib\site-packages - 以系統管理員身分,開啟Anaconda Prompt,切換至eric6解壓縮後的目錄下
C:\ProgramData\Anaconda3\Lib\site-packages\eric6-19.7 - 安裝 eric6
(base) C:\ProgramData\Anaconda3\Lib\site-packages\eric6-19.7>python install.py install
Checking dependencies
Python Version: 3.7.3
Found PyQt5
Found pyuic5
QScintilla could not be detected.
Error: cannot import name 'Qsci' from 'PyQt5' (C:\ProgramData\Anaconda3\lib\site-packages\PyQt5\__init__.py)
Shall 'QScintilla' be installed using pip? (Y/n) Y
Collecting QScintilla
Downloading https://files.pythonhosted.org/packages/52/1a/ce7875f433fd0aa1d3774609586f77d78ff0524790942cca95e1d13a7ac7/QScintilla-2.11.2-5.12.4-cp35.cp36.cp37.cp38-none-win_amd64.whl (2.0MB)
...
Collecting PyQt5>=5.10.1 (from QScintilla)
Downloading https://files.pythonhosted.org/packages/3b/d3/76670a331935f58f9a2ebd53c6e9b670bbf15c458fa6993500af5d323160/PyQt5-5.13.0-5.13.0-cp35.cp36.cp37.cp38-none-win_amd64.whl (49.7MB)
...
Collecting PyQt5_sip<13,>=4.19.14 (from PyQt5>=5.10.1->QScintilla)
Downloading https://files.pythonhosted.org/packages/cf/c8/1e9eda4ba09a84fc528d4c87001de2d7a8cbbe04c2a834af3eb81a0ecd88/PyQt5_sip-4.19.18-cp37-none-win_amd64.whl (51kB)
...
ERROR: spyder 3.3.6 requires pyqtwebengine<5.13; python_version >= "3", which is not installed.
ERROR: spyder 3.3.6 has requirement pyqt5<5.13; python_version >= "3", but you'll have pyqt5 5.13.0 which is incompatible.
Installing collected packages: PyQt5-sip, PyQt5, QScintilla
ERROR: Could not install packages due to an EnvironmentError: [WinError 5] 存取被拒。: 'C:\\ProgramData\\Anaconda3\\Lib\\site-packages\\PyQt5\\QtCore.pyd'
Consider using the `--user` option or check the permissions.
Sorry, please install QScintilla2 and
its PyQt5/PyQt4 wrapper.
Error: QScintilla could not be installed.
Press enter to continue... - eric6安裝發生錯誤的原因:
安裝eric6需要安裝QScintilla,需要PyQt5 5.10.1 以上的版本,系統自動收集安裝了 pyqt5 5.13.0的版本。
但已安裝的spyder 3.3.6 限制 pyqt5 必須是 v5.13以下 (<5.13) - 重新安裝pyqt5-tools,並指定安裝版本為 5.11.3
(base) C:\ProgramData\Anaconda3>pip install pyqt5==5.11.3
Collecting pyqt5==5.11.3
Downloading https://files.pythonhosted.org/packages/a7/2d/d2c989006c86ae98ed230c28c3e0dd7fa0374e723afc107d12268159ceb7/PyQt5-5.11.3-5.11.2-cp35.cp36.cp37.cp38-none-win_amd64.whl (93.4MB)
...
ERROR: spyder 3.3.6 requires pyqtwebengine<5.13; python_version >= "3", which is not installed.
Installing collected packages: pyqt5
Successfully installed pyqt5-5.11.3 - 安裝pyqt5-tools
(base) C:\ProgramData\Anaconda3>pip install pyqt5-tools
Collecting pyqt5-tools
Downloading https://files.pythonhosted.org/packages/6a/35/98279ba706e9c3731f0f53813e9a8152ed662f2230e8af18a20d490167be/pyqt5_tools-5.11.3.1.4-cp37-none-win_amd64.whl (59.4MB)
...
Requirement already satisfied: pyqt5==5.11.3 in c:\programdata\anaconda3\lib\site-packages (from pyqt5-tools) (5.11.3)
Requirement already satisfied: click in c:\programdata\anaconda3\lib\site-packages (from pyqt5-tools) (7.0)
Collecting python-dotenv (from pyqt5-tools)
Downloading https://files.pythonhosted.org/packages/57/c8/5b14d5cffe7bb06bedf9d66c4562bf90330d3d35e7f0266928c370d9dd6d/python_dotenv-0.10.3-py2.py3-none-any.whl
Requirement already satisfied: PyQt5_sip<4.20,>=4.19.11 in c:\programdata\anaconda3\lib\site-packages (from pyqt5==5.11.3->pyqt5-tools) (4.19.18)
Installing collected packages: python-dotenv, pyqt5-tools
Successfully installed pyqt5-tools-5.11.3.1.4 python-dotenv-0.10.3 - 安裝 eric6
(base) C:\ProgramData\Anaconda3\Lib\site-packages\eric6-19.7>python install.py install
Checking dependencies
Python Version: 3.7.3
Found PyQt5
Found pyuic5
QScintilla could not be detected.
Error: cannot import name 'Qsci' from 'PyQt5' (C:\ProgramData\Anaconda3\lib\site-packages\PyQt5\__init__.py)
Shall 'QScintilla' be installed using pip? (Y/n) Y
Collecting QScintilla
Using cached https://files.pythonhosted.org/packages/52/1a/ce7875f433fd0aa1d3774609586f77d78ff0524790942cca95e1d13a7ac7/QScintilla-2.11.2-5.12.4-cp35.cp36.cp37.cp38-none-win_amd64.whl
Requirement already satisfied: PyQt5>=5.10.1 in c:\programdata\anaconda3\lib\site-packages (from QScintilla) (5.11.3)
Requirement already satisfied: PyQt5_sip<4.20,>=4.19.11 in c:\programdata\anaconda3\lib\site-packages (from PyQt5>=5.10.1->QScintilla) (4.19.18)
Installing collected packages: QScintilla
Successfully installed QScintilla-2.11.2
Found QScintilla2
Found QtGui
Found QtNetwork
Found QtPrintSupport
Found QtSql
Found QtSvg
Found QtWidgets
Found QtWebEngineWidgets
Qt Version: 5.11.2
sip Version: 4.19.18
PyQt Version: 5.11.3
QScintilla Version: 2.11.2
All dependencies ok.
Cleaning up old installation ...
Creating configuration file ...
Compiling user interface files ...
Compiling source files ...
Installing eric6 ...
Installing Python API files to 'C:/ProgramData/Anaconda3/lib/site-packages/PyQt5/Qt\qsci\api\python'.
Installing Ruby API files to 'C:/ProgramData/Anaconda3/lib/site-packages/PyQt5/Qt\qsci\api\ruby'.
Installing QSS API files to 'C:/ProgramData/Anaconda3/lib/site-packages/PyQt5/Qt\qsci\api\qss'.
Installation complete.
Press enter to continue... - 安裝 eric6 成功
- 確認可以啟動 spyder
- 確認可以啟動designer.exe
- 確認可以啟動 eric6
訂閱:
文章 (Atom)