簡體   English   中英

批處理文件使用 sys.argv[] 執行 Python 腳本

[英]Batch file executes Python script with sys.argv[]

我為執行 python 腳本的 windows 終端創建了一個自定義命令scan

@echo off
python "my_scripts\scan.py"

對於初始測試,我編寫了這個絕妙的腳本。

import sys

print(f"The name of the script is: { sys.argv[0] }")

當我在 shell 中輸入scan時,據我所知,這應該只是打印: The name of the script is: scan

但相反,我得到的 output 是: The name of the script is: my_scripts\scan.py

問題很明顯,但我不知道如何解決這個問題。

您可以使用Path.stem獲取不帶擴展名的文件名

__file__是當前文件的完整路徑,您可以將其傳遞給Path

from pathlib import Path

print(f"The name of the script is: {Path(__file__).stem}")

如果您願意,您也可以傳遞sys.argv[0]

from pathlib import Path
import sys

print(f"The name of the script is: {Path(sys.argv[0]).stem}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM