簡體   English   中英

在Python腳本中運行終端

[英]Running Terminal within a Python Script

我正在嘗試通過Python腳本在終端中運行命令。 該命令只有三個參數,在終端中執行時效果很好。 這是在命令行中輸入的內容:

gpmetis inputfile numberOfSections

無論在inputfile是從,說桌面時, outputfile后在同一地點傾倒gpmetis執行(它被命名為inputfile.part.numberOfSections )。 gpmetis僅在終端中工作,但出於壓縮的目的,我想在Python腳本的中間使用它以節省時間。 (我以前只是在終端和Python之間來回移動文件)

但是,這是我遇到的問題......這個問題,而這個論壇就如何Python的范圍內執行終端有用的提示,但我仍未收到該outputfile當我運行Python代碼。 就像輸出被抑制或我呼叫終端的方式有問題。

我目前正在打電話給終端,例如:

def Terminal(inputfile, NumParts): 
    os.system("gpmetis inputfile NumParts")

    outputfile = "inputfile.part." + NumParts
    return outputfile

而且我沒有從中得到任何錯誤,但是我也沒有收到任何輸出文件。 我在這里想念的是什么,如果您知道,您可以解釋一下嗎? 我正在嘗試學習Python,因此不勝感激地描述我正在搞砸的內容。

os已導入。 可能有怎樣我“回歸”的故障outputfile在我的劇本,但我還沒有看到一個outputfile我的桌面,這是第一個問題要處理上(一步一個腳印的時間!)

注意:我找到了相關的文檔 ,但是對我有幫助嗎? 我在理解它時遇到了麻煩。

首先,您可以檢查os.system的返回值。 非零返回值通常表示已發生錯誤。

看來您正在嘗試使用命令中的參數。 在這種情況下,它應該看起來像:

def Terminal(inputfile, NumParts): 
    command = 'gpmetis ' + inputfile + ' ' + str(NumParts)
    os.system(command)

    outputfile = intputfile + '.part.' + str(NumParts)
    return outputfile

最后,根據答案,看起來您最好使用subprocess模塊。 然后可以執行相同的命令,如下所示:

import subprocess
subprocess.call(['gpmetis', inputfile, str(NumParts)])

這里的inputfile是傳遞給函數的變量,但是在命令行參數中,它被當作文件名。

您可能要嘗試

os.system('gpmetis ' + str(inputfile) + ' ' + str(NumParts))
outputfile = intputfile + '.part.' + str(NumParts)

沒有調用代碼和意圖很難說。 讓我知道是否有幫助。

暫無
暫無

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

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