在這 16 個小時里,我一直把頭撞在墻上,我似乎找不到任何有完全相同問題的人。
我有一個命令列程式(我將其稱為 CLI),我正在使用它作為引數一個文本檔案,其中檔案的每一行都有重要資訊。無需詳述,CLI 將檔案的行傳遞給完成某些操作的 Web 服務。
我有一個我正在撰寫的 python 程式,我在其中創建以編程方式傳遞給 CLI 的檔案(使用子行程)。問題似乎是 Web 服務在某個不知道如何處理的地方收到回車。在創建進入該檔案的每一行時,我非常小心地避免任何回車,但顯然回車被添加到末尾。我以二進制模式打開我的檔案,果然,有回車。真可惜。
無論如何,我一直在這里看到一個共享腳本,顯示如何將檔案從 CRLF 轉換為 LF。將這幾行添加到我的 python 腳本中,并仔細檢查并確定,當以二進制模式讀取檔案時,回車消失了。歡呼。
但是當我再次運行腳本時,由于某種原因,Web 服務仍在接收回車。
我懷疑它與我正在使用的 python 臨時檔案系統有關。也許它在后臺以某種奇怪的方式作業,并且在我將檔案更改為使用 LF 并列印其內容之后,在某個時候將其更改回來(也許當它作為引數傳遞給 CLI 時)
我想我的問題是,要么 1)即使看起來我已經更改了它們,你能想出一些 tempfile 可能會弄亂我的檔案結尾的東西嗎?也許當臨時檔案通過子行程傳遞到cli時,它會以某種方式恢復?我只是用 temp.name 發送它。
或者2)也許我可以做一些除了python內置的臨時檔案之外的事情。它真的很方便,所以如果我不打算使用它,是否有一些我應該知道的手動創建和洗掉臨時檔案的最佳實踐?有沒有最好的地方來創建它們?例如,直接從當前目錄創建然后洗掉檔案是否被認為是不好的做法?
無論如何,在更改行尾之后,這是我的代碼的相關部分:
def my_function(mylist, my_id, local_id, args):
temp = tempfile.NamedTemporaryFile(mode='w b', delete=False)
for each in mylist:
is_directory = False
destination = args.destination.replace("\\", "/")
if each["smallpath"] == "/":
full_path = each["smallpath"] "/"
else:
full_path = each["rel_path"].replace("\\", "/") "/" each["specific_path"].lstrip("/")
if os.path.basename(full_path) == "":
is_directory = True
if is_directory is False:
line = f'"{full_path}" "~/{destination}/{each["orgID"]}-{each["userID"]}/{os.path.basename(full_path)}" \n'
else:
if each["smallpath"] != "/":
slash_index = full_path.rstrip('/').rfind("/")
local_dir = full_path[slash_index:].rstrip().rstrip('/')
else:
local_dir = "/"
line = f'"{full_path}" "~/{destination}/{each["orgID"]}-{each["userID"]}/{local_dir.lstrip("/")}" --recursive \n'
line = line.replace("\\", "/")
temp.write(line)
temp.seek(0)
windows_ending = b'\r'
unix_ending = b'\n'
double_newline = b'\n\n'
with open(temp.name, 'rb') as file:
file_contents = file.read()
temp.seek(0)
file_contents = file_contents.replace(windows_ending, unix_ending)
file_contents = file_contents.replace(double_newline, unix_ending)
with open(temp.name, 'wb') as file:
file.write(file_contents)
myprocess = subprocess.Popen(["programname", "commandname", myid, local_id, "--batch",
temp.name], stdout=subprocess.PIPE)
mycommand = myprocess.communicate()[0].decode('utf-8')
temp.close()
os.unlink(temp.name)
uj5u.com熱心網友回復:
我要感謝所有試圖提供幫助的人。這些評論幫助我發現了代碼中其他地方的另一個漏洞。問題最終不是我自己的,而是我使用的服務
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/452550.html
下一篇:如何安全地終止多執行緒行程
