DEV Community

codemee
codemee

Posted on

VSCode 中讓 Python script 在所屬資料夾中執行程式

在 VSCode 中若開啟資料夾中的 Python script,預設執行時還是會以 VSCode 終端機所在的路徑執行,這樣對於 scipt 中以相對路徑表示的檔案或是路徑,就會找不到,例如:

 meebo on  ~/code/python/fusion_pixel_font master 
# & C:/Users/meebo/code/python/fusion_pixel_font/.venv/Scripts/python.exe c:/Users/meebo/code/python/fusion_pixel_font/tools/make_bitmap_font.py
C:\Users\meebo\code\python\fusion_pixel_font\tools\make_bitmap_font.py
Traceback (most recent call last):
  File "c:\Users\meebo\code\python\fusion_pixel_font\tools\make_bitmap_font.py", line 8, in <module>
    font = bdfparser.Font("../fonts/fusion-pixel-12px-monospaced-zh_hant.bdf")
  File "C:\Users\meebo\code\python\fusion_pixel_font\.venv\Lib\site-packages\bdfparser\bdfparser.py", line 92, in __init__
    self.load_file_path(arg)
    ~~~~~~~~~~~~~~~~~~~^^^^^
  File "C:\Users\meebo\code\python\fusion_pixel_font\.venv\Lib\site-packages\bdfparser\bdfparser.py", line 103, in load_file_path
    with open(file_path) as file_obj:
         ~~~~^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: '../fonts/fusion-pixel-12px-monospaced-zh_hant.bdf'
Enter fullscreen mode Exit fullscreen mode

由於 VSCode 終端機現在的路徑是 ~/code/python/fusion_pixel_font,但我執行的是位於 c:\Users\meebo\code\python\fusion_pixel_font\tools\ 下的 make_bitmap_font.py 檔,因此當我要開啟以相對路徑表示的 ../fonts/fusion-pixel-12px-monospaced-zh_hant.bdf 檔時就會找不到檔案。為了解決這個問題,必須勾選 Python 延伸模組的以下設定:

Image description

在設定檔中的項目為:

"python.terminal.executeInFileDir": true,
Enter fullscreen mode Exit fullscreen mode

這樣在執行 sciprt 之前,會先切換到 script 所在的資料夾,就可以正確執行了。

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay