我試圖制作一個從網站獲取 .txt 的腳本,將代碼粘貼到 python 可執行臨時檔案中,但它不起作用。這是代碼:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
import tempfile
filename = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt")
temp = open(filename)
temp.close()
# Clean up the temporary file yourself
os.remove(filename)
temp = tempfile.TemporaryFile()
temp.close()
如果您知道解決此問題的方法,請告訴我。錯誤是:
File "test.py", line 9, in <module>
temp = open(filename)
TypeError: expected str, bytes or os.PathLike object, not HTTPResponse
我嘗試了所有方法,例如對 url 的請求并粘貼它,但效果不佳。我嘗試了粘貼在此處的代碼,但效果不佳。
正如我所說,我期待它從網站的 .txt 中獲取代碼,并使其成為一個臨時的可執行 python 腳本
uj5u.com熱心網友回復:
你錯過了閱讀:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
import tempfile
filename = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt").read() # <-- here
temp = open(filename)
temp.close()
# Clean up the temporary file yourself
os.remove(filename)
temp = tempfile.TemporaryFile()
temp.close()
但是如果script.txt包含腳本而不是檔案名,則需要創建一個臨時檔案并寫入內容:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
import tempfile
content = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt").read() #
with tempfile.TemporaryFile() as fp:
name = fp.name
fp.write(content)
如果你想執行你從 url 中獲取的代碼,你也可以使用execoreval而不是撰寫一個新的腳本檔案。
eval并且exec是 EVIL,只有當您 100% 信任輸入并且沒有其他方法時才應該使用它們!
編輯:我如何使用 exec?
使用 exec,你可以做這樣的事情(另外,我在這里使用 requests 而不是 urllib。如果你更喜歡 urllib,你也可以這樣做):
import requests
exec(requests.get("https://randomsiteeeee.000webhostapp.com/script.txt").text)
uj5u.com熱心網友回復:
您試圖打開一個名為“網站內容”的檔案。
filename = "path/to/my/output/file.txt"
httpresponse = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt").read()
temp = open(filename)
temp.write(httpresponse)
temp.close()
可能更像你想要的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/534252.html
標籤:Python要求临时文件
上一篇:行程以退出代碼0python完成
