Can't run binary from within python aws lambda function

前端 未结 6 1889
一生所求
一生所求 2021-01-11 16:57

I am trying to run this tool within a lambda function: https://github.com/nicolas-f/7DTD-leaflet

The tool depends on Pillow which depends on imaging libraries not av

6条回答
  •  难免孤独
    2021-01-11 17:30

    I know I'm a bit late for this but if you want a more generic way of doing this (for instance if you have a lot of binaries and might not use them all), this how I do it, provided you put all your binaries in a bin folder next to your py file, and all the libraries in a lib folder :

    import shutil
    import time
    import os
    import subprocess
    
    LAMBDA_TASK_ROOT = os.environ.get('LAMBDA_TASK_ROOT', os.path.dirname(os.path.abspath(__file__)))
    CURR_BIN_DIR = os.path.join(LAMBDA_TASK_ROOT, 'bin')
    LIB_DIR = os.path.join(LAMBDA_TASK_ROOT, 'lib')
    ### In order to get permissions right, we have to copy them to /tmp
    BIN_DIR = '/tmp/bin'
    
    # This is necessary as we don't have permissions in /var/tasks/bin where the lambda function is running
    def _init_bin(executable_name):
        start = time.clock()
        if not os.path.exists(BIN_DIR):
            print("Creating bin folder")
            os.makedirs(BIN_DIR)
        print("Copying binaries for "+executable_name+" in /tmp/bin")
        currfile = os.path.join(CURR_BIN_DIR, executable_name)
        newfile  = os.path.join(BIN_DIR, executable_name)
        shutil.copy2(currfile, newfile)
        print("Giving new binaries permissions for lambda")
        os.chmod(newfile, 0775)
        elapsed = (time.clock() - start)
        print(executable_name+" ready in "+str(elapsed)+'s.')
    
    # then if you're going to call a binary in a cmd, for instance pdftotext :
    
    _init_bin('pdftotext')
    cmdline = [os.path.join(BIN_DIR, 'pdftotext'), '-nopgbrk', '/tmp/test.pdf']
    subprocess.check_call(cmdline, shell=False, stderr=subprocess.STDOUT)
    

提交回复
热议问题