根据https://github.com/zdenulo/google-cloud-functions-system-packages/tree/master/cf_ascii的示例,我正在尝试使用Google Cloud Function中的子进程运行二进制文件:
import os
import subprocess
import logging
from flask import make_response
def main(request):
text = request.args.get('text', '')
if not text:
return 'missing text parameter', 404
logging.info(f'received url: {text}')
cmd = f"./figlet -d fonts {text}".split(' ')
p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
error = stderr.decode('utf8')
if error:
return error, 403
out = stdout.decode('utf8')
response = make_response(out)
response.headers["content-type"] = "text/plain"
return response
根据我的阅读,这应该是可能的,但是在执行它时出现此错误:
...
File "/opt/python3.7/lib/python3.7/subprocess.py", line 1522, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
PermissionError: [Errno 13] Permission denied: './figlet'
因此该功能似乎缺少正确的权限,但是我无法弄清楚原因(文件权限设置,IAM /服务帐户权限...)。我在这里想念什么?
错误向我提示./figlet没有设置其可执行位。您应该确保在部署之前是这种情况:
chmod a+x figlet
如果从Windows进行部署,除了要从中部署linux或macos机器,您可能没有其他选择。
您需要相对于源文件所在的位置(而不是相对于从其执行文件的位置)创建文件的路径。在Cloud Functions上调用您的函数时,它们是不同的。
尝试以下操作:
import os
this_dir, this_filename = os.path.split(__file__)
path_to_figlet = os.path.join(this_dir, 'figlet')
cmd = [path_to_figlet, '-d', 'fonts', text]