簡體   English   中英

用於命令行自動化的 Python os.system 或子進程調用

[英]Python os.system or subprocess calls for command line automation

我希望能夠調用一些接受參數的可執行文件,然后將輸出轉儲到文件中。 我試圖同時使用 os.system 和 subprocess 調用都無濟於事。 這是我希望 python 為我執行的示例...

c:\directory\executable_program.exe -f w:\directory\input_file.txt > Z\directory\output_file.txt

請注意絕對路徑,因為我將遍歷數百個不同的目錄來處理文件等。

非常感謝提前!

我試過的一些例子:

subprocess.run(['c:\directory\executable_program.exe -f w:\directory\input_file.txt > Z\directory\output_file.txt']

subprocess.call(r'"c:\directory\executable_program.exe -f w:\directory\input_file.txt > Z\directory\output_file.txt"']

subprocess.call(r'"c:\directory\executable_program.exe" -f "w:\directory\input_file.txt > Z\directory\output_file.txt"']

您的嘗試包含各種數量的引用錯誤。

subprocess.run(r'c:\directory\executable_program.exe -f w:\directory\input_file.txt > Z\directory\output_file.txt', shell=True)

應該可以工作,其中r前綴保護反斜杠在子進程運行之前不被 Python 解釋和刪除,並且值周圍沒有[...]將其逐字傳遞給 shell(因此, shell=True )。

在 Windows 上,即使它不是列表,您也可以將命令放在方括號中,並且在某些情況下省略shell=True

如果您想避免使用外殼,請嘗試

with open(r'Z\directory\output_file.txt', 'wb') as dest:
    subprocess.run(
        [r'c:\directory\executable_program.exe', '-f', r'w:\directory\input_file.txt'],
        stdout=dest)

它還說明了如何正確地將方括號中的字符串列表作為第一個參數傳遞給subprocess.run

暫無
暫無

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

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