簡體   English   中英

使用 applescript 從 python 腳本打開終端 window 並執行腳本

[英]Opening terminal window from python script using applescript and execute a script

我有一個 python 腳本“test.py”,它需要 arguments 50-100-150 等批次。

每次我必須打開多個終端 windows(10-15 個窗口)並手動執行“test.py”提供批次(一段時間后詳盡無遺)

我決定單獨編寫一個腳本,通過批量提供 arguments 遞歸打開終端 window。

短腳本運行良好,但如果腳本文件路徑中有空格,則會拋出錯誤。 我嘗試了 inte.net 上提供的多種解決方案,但似乎都不起作用

短代碼片段: from applescript import tell yourCommand = 'python3 ~/Desktop/untitled folder/test.py <range of batch, Ex: 1 51>' tell.app( 'Terminal', 'do script "' + yourCommand + ' "')

到目前為止我已經嘗試過:

  1. 用雙引號將文件夾括起來,例如:“無標題文件夾”
  2. 使用“r”,例如:yourCommand = r'"python3 ~/Desktop/untitled folder/test.py <range of batch, Ex: 1 51>"'
  3. 使用反斜杠,例如:untitled\ folder
  4. 使用雙反斜杠,例如:untitled\ folder

但每次終端 window 未打開或打開時,它都會拋出錯誤“/Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python:無法打開文件'/Users//Desktop/untitled': [Errno 2] 沒有這樣的文件或目錄”

環境:Mac OSX

任何幫助,將不勝感激。 我確定我一定犯了一些愚蠢的錯誤,但無法解決。

截圖:

腳本 1.py 腳本 1.py

1.py 的 output 1.py的輸出

使用do shell 腳本時:

do shell script "python3 ~/Desktop/untitled\\ folder/test.py"

在終端中鍵入或使用do script命令時:

tell application "Terminal"
    do script "python3 ~'/Desktop/untitled folder/test.py'"
end tell

最佳做法是使用引號形式進行轉義。 在終端中復制文件夾示例:

set theSource to "/Desktop/TESTFiles/"
set theDestination to "/Desktop/TEST Files/"

tell application "Terminal"
    do script "ditto ~" & quoted form of theSource & " ~" & quoted form of theDestination
end tell

do shell 腳本中的相同任務以及引用的形式需要先確定主文件夾路徑。 也就是說,而不是代字號:

set home to POSIX path of (path to home folder)
set theSource to quoted form of (home & "/Desktop/TESTFiles/")
set theDestination to quoted form of (home & "/Desktop/TEST Files/")

do shell script "ditto " & theSource & " " & theDestination

將以下python腳本保存為桌面untitled folder文件夾中的print trianlges.py文件。

max_size = 10

print(
    "(a)" + " " * (max_size) +
    "(b)" + " " * (max_size) +
    "(c)" + " " * (max_size) +
    "(d)" + " " * (max_size)
    )

for i in range(1, max_size + 1):

    print("*" * i, end = " " * (max_size - i + 3))

    print("*" * (max_size - i + 1), end = " " * (i - 1 + 3))

    print(" " * (i - 1) + "*" * (max_size - i + 1), end = " " * 3)

    print(" " * (max_size - i) + "*" * i)

現在,在終端中運行以下命令來打印三角形。 如您所見,該路徑在文件夾名稱和文件名稱中都有空格,並且工作正常:

python3 ~'/Desktop/untitled folder/print triangles.py'

暫無
暫無

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

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