节点无法读取python保存的文件
Posted
技术标签:
【中文标题】节点无法读取python保存的文件【英文标题】:Node can't read file saved by python 【发布时间】:2021-08-05 20:06:44 【问题描述】:我正在通过节点 child_process 运行 python 脚本。此 python 脚本将文件下载到磁盘,然后将文件名返回给节点。我遇到的问题是python保存的文件直到节点进程关闭后才会出现在我的文件目录中(由于它试图读取python保存的这个文件而引发错误)。我不确定如何让 python “立即”保存文件,以便我的节点进程可以读取它。
节点代码:
var sent = false;
const CP = require("child_process");
var process = CP.spawn('python', ["../pyScripts/download.py", vid_url]);
process.stdout.on('data', function(data)
console.log("recieved data")
if(sent === false)
sent = true
process.kill('SIGINT');
doStuffWithFile(`$data.toString().mp4`);
);
Python 代码:
#*code that grabs file bytes*
with open(f'filename.mp4', "wb") as out:
out.write(vid_bytes)
print(filename)
【问题讨论】:
【参考方案1】:当您写入文件时,不要忘记关闭它。试试这个:
#*code that grabs file bytes*
with open(f'filename.mp4', "wb") as out:
out.write(vid_bytes)
out.close()
print(filename)
【讨论】:
这似乎也不起作用。我的节点进程终止的那一刻,该文件出现在我的目录中。这让我想也许它必须做节点的 child_process 功能? 也许,但不关闭文件仍然是一种不好的做法【参考方案2】:等待退出事件,表示 Python 进程已完成。
node.js:
var filename = '';
var sent = false;
var fs = require("fs");
const cp = require("child_process");
var process = cp.spawn('python3', ["/tmp/foo.py", "https://dl8.webmfiles.org/elephants-dream.webm"]);
process.stdout.on('data', (data) =>
console.log(`stdout: $data`);
filename = data.toString().trim(); // remove trailing new line!
);
process.on('exit', (code) =>
console.log(`child process exited with code $code`);
console.log('Reading: ' + filename)
var stats = fs.statSync(filename)
var fileSizeInBytes = stats.size;
var fileSizeInMegabytes = fileSizeInBytes / (1024*1024);
console.log(`Python downloaded $fileSizeInMegabytes MB`)
);
Python:
import time
import requests
import sys
import shutil
filename = '/tmp/test.webm'
headers = 'User-Agent': 'Mozilla 5.0'
response = requests.get(sys.argv[1], stream=True, headers=headers)
with open(filename, 'wb') as out_file: # with open(...) closes the file automatically
shutil.copyfileobj(response.raw, out_file)
print(filename)
输出:
stdout: /tmp/test.webm
child process exited with code 0
Reading: /tmp/test.webm
Python downloaded 8.169429779052734 MB
【讨论】:
以上是关于节点无法读取python保存的文件的主要内容,如果未能解决你的问题,请参考以下文章
如何将各种尺寸的数组的Python列表保存到mat文件[重复]