今天要測試直接用指令 call vertex ai workbench,我們一樣保留 main.py
import logging
import time
import requests
# import langchain
# 配置日誌
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
def main():
logging.info("開始執行腳本")
for i in range(5):
logging.info(f"這是第 {i+1} 條日誌訊息")
time.sleep(1) # 暫停1秒,模擬處理時間
logging.info("腳本執行完畢")
if __name__ == "__main__":
main()
然後設定 init.pynb
import subprocess
import sys
def run_main_py():
try:
# 使用 subprocess 執行 main.py,捕獲 stdout 和 stderr
result = subprocess.run([sys.executable, 'main.py'],
capture_output=True,
text=True,
check=True)
# 輸出執行結果
print("main.py 執行成功!")
print("標準輸出(stdout):")
print(result.stdout)
print("標準錯誤(stderr):")
print(result.stderr)
except subprocess.CalledProcessError as e:
print("執行 main.py 時發生錯誤:")
print("標準輸出(stdout):")
print(e.stdout)
print("標準錯誤(stderr):")
print(e.stderr)
# 執行函數
run_main_py()
然後從本地端觸發檔案
gcloud compute ssh vertical-ai-workbench \
--project=shopeetwbi \
--zone=asia-east1-a \
--command="export HOME=/home/alvin_linpy_shopee_com && cd /home/alvin_linpy_shopee_com && /opt/conda/bin/conda run -n jupyterlab jupyter nbconvert --to notebook --execute /home/jupyter/bi-portal-infra/init.ipynb --output /home/alvin_linpy_shopee_com/executed_init.ipynb --ExecutePreprocessor.kernel_name=python3"
然後下載最終執行檔
gcloud compute scp vertical-ai-workbench:/home/alvin_linpy_shopee_com/executed_init.ipynb ./executed_init.ipynb \
--project=shopeetwbi \
--zone=asia-east1-a
executed_init.ipynb
就會在 output 看到結果了
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"main.py 執行成功!\n",
"標準輸出(stdout):\n",
"\n",
"標準錯誤(stderr):\n",
"2024-10-13 13:38:41,816 - 開始執行腳本\n",
"2024-10-13 13:38:41,816 - 這是第 1 條日誌訊息\n",
"2024-10-13 13:38:42,817 - 這是第 2 條日誌訊息\n",
"2024-10-13 13:38:43,818 - 這是第 3 條日誌訊息\n",
"2024-10-13 13:38:44,819 - 這是第 4 條日誌訊息\n",
"2024-10-13 13:38:45,821 - 這是第 5 條日誌訊息\n",
"2024-10-13 13:38:46,822 - 腳本執行完畢\n",
"\n"
]
}
]