簡體   English   中英

Python:子進程不寫入輸出文件

[英]Python: subprocess not writing output files

使用 Python 的subprocess.call ,我試圖調用一個 C 程序來讀取磁盤上的輸入文件,並創建多個輸出文件。 從終端運行 C 程序會得到預期的結果,但subprocess.call不會。

在最小的例子中,程序應該讀取臨時文件夾中的輸入文件,並在同一個文件夾中創建一個輸出文件。 輸入和輸出文件的位置和名稱被硬編碼到 C 程序中。

import subprocess


subprocess.call('bin/program.exe') # parses input file 'scratch/input.txt'
with open('scratch/output.txt') as f:
    print(f.read())

這將返回:

FileNotFoundError: [Errno 2] No such file or directory: 'scratch/output.txt'

我究竟做錯了什么?

使用subprocess.check_output ,我看不到任何錯誤。

編輯:所以我看到涉及子進程工作目錄。 C 可執行文件具有相對於 exe 的輸入/輸出的硬編碼路徑(即,'../scratch/input.txt'),但 subprocess.call subprocess.call()調用需要相對於 python 腳本的路徑,而不是 exe。 這是出乎意料的,並且與從終端調用 exe 產生非常不同的結果。

import os

subprocess.call('bin/program.exe') # parses input file 'scratch/input.txt'
if not os.path.isfile('scratch'):
    os.mkdir('scratch')
with open(os.path.join('scratch','output.txt'), 'w') as f:
    f.write('Your message')

您必須以一種模式打開文件。 以閱讀為例。 您需要使用 os.path.join() 加入路徑。

如果文件夾和文件不存在,您可以創建它們。 但是沒有什么可閱讀的。 如果你想寫信給他們,可以如上所示實現。

暫無
暫無

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

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