[英]In Python, why can't you parse a file immediately after it is created using subprocess?
我正在嘗試讀取一個輸入文件(下面列為“ infile2”,它可以是任何文件),對於此文件中的每一行,請創建File2,然后解析File2以創建File3。 不管我為什么要用這種方式進行編碼(除非這是原因,這當然是一個問題……),為什么第一段代碼有效,而下一段失敗?
#!/usr/bin/env python
import sys
import subprocess
#THIS WORKS
def CreateFile():
command = "echo 'Here is some text' > CreateFile.txt"
subprocess.Popen(command,shell=True)
def Parse():
with open("CreateFile.txt") as infile1:
for line in infile1:
return line
if __name__ == '__main__':
infile2 = sys.argv[1]
with open(infile2) as f:
for line in f:
CreateFile()
with open(infile2) as g:
print Parse()
outfile=open("CreateFile.txt",'w')
#!/usr/bin/env python
import sys
import subprocess
def CreateFile():
command = "echo 'Here is some text' > CreateFile.txt"
subprocess.Popen(command,shell=True)
def Parse():
with open("CreateFile.txt") as infile1:
for line in infile1:
return line
if __name__ == '__main__':
infile2 = sys.argv[1]
with open(infile2) as f:
for line in f:
CreateFile()
print Parse()
outfile=open("CreateFile.txt",'w')
第二個塊產生此錯誤:IOError:[Errno 2]沒有這樣的文件或目錄:'CreateFile.txt'python解釋器是否不等到上一行完成?
從文檔 -
在新進程中執行子程序。
Popen啟動該過程並繼續執行主線程。 你seeeing的問題是最有可能是因為您開具使用命令Popen
尚未被你試圖打開的時間完成CreateFile.txt
。 這在第二個腳本中更為明顯,因為您嘗試在發出命令之后立即打開CreateFile.txt
,而在第一個腳本中,這兩個操作之間有一些語句。
嘗試使用.wait()
方法,在執行命令之前等待進程完成,例如-
def CreateFile():
command = "echo 'Here is some text' > CreateFile.txt"
subprocess.Popen(command,shell=True).wait()
或者,如果您只想運行命令,也可以使用subprocess.call()
(如果您的情況與所發布的代碼一樣簡單,則建議在Popen上這樣做)。 從文檔中-
運行args描述的命令。 等待命令完成,然后返回returncode屬性。
范例-
def CreateFile():
command = "echo 'Here is some text' > CreateFile.txt"
subprocess.call(command,shell=True)
python解釋器是否不等到上一行完成?
如果上一行是,則不是: subprocess.Popen(command,shell=True)
Popen()
創建一個異步過程並立即返回。 如果要等待進程完成,請嘗試subprocess.call()
或subprocess.check_call
。
您正在使用subprocess.Popen
創建文件,這將啟動一個新進程。 之后,執行將繼續,並且您已經在嘗試打開正在創建的文件。
您應該等待子過程完成。 你可以做到這一點與.wait()
的方法Popen
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.