Run Python3 without activating the virtual environment

2024/10/15 7:22:12

My objective is to run Python 3 code on the AWS Lambda Service, which currently only supports Python 2.7. These are the steps I have done.

  • Since I work on a Mac, setup a docker image similar to the AWS Lambda Linux instance.

  • Build Python3 from source on the docker image.

  • In the docker image create a virtual environment and copy it to my project.

  • AWS Lambda requires you to create a zip of the code and upload it to their service. For this prototype, I have a zip with three artifacts at the root

    1. handler.py: This is a Python 2.7 file. The handler function in this file will be executed by the AWS Lambda Service when an event occurs (e.g. When a new file is created in a S3 bucket).

      def handler(event, context):execution_uuid = uuid.uuid4()commands = '''source venv/bin/activate && venv/bin/python3.6 ./handler_python3.py --execution_uuid {ex_uuid}'''.format(ex_uuid=str(execution_uuid))p = Popen('/bin/bash', shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)stdout, stderr = p.communicate(commands)pprint(stdout)pprint(stderr)
      
    2. handler_python3.py. This is the Python3 file called by the earlier handler.py file. Note the execution_uuid being read. I have taken out the code that uses it for brevity but I do need it and I am using argparse to extract it.

      def read_execution_uuid():import argparseparser = argparse.ArgumentParser()parser.add_argument("--execution_uuid", required=True)args = parser.parse_args()return args.execution_uuiddef handler(event, context):import sysprint(sys.path)if __name__ == '__main__':execution_uuid = read_execution_uuid()handler(event, context)
      
      1. venv folder. This is the virtual environment folder that I copied from the docker image.

When I run the AWS Lambda Service, I get the following error

Traceback (most recent call last):File "./handler_python3.py", line 38, in <module>execution_uuid = read_execution_uuid()File "./handler_python3.py", line 7, in read_execution_uuidimport argparse
ModuleNotFoundError: No module named \'argparse\'

Notes:

  • If I remove the argparse code and the handler function in handler_python3.py executes, it shows the following values for sys.path

    ['/var/task', '/var/runtime', '/var/task/venv/lib/python36.zip', '/var/task/venv/lib/python3.6', '/var/task/venv/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6', '/var/task/venv/lib/python3.6/site-packages']
    

Notes:

  • I can install argparse explicitly. But I'd like not to.
  • Note the source venv/bin/activate command in the python 2.7 file handler.py. That doesn't work on the Lambda instance though it works locally.
Answer

Creating a virtual environment does not copy all the modules from the /usr/local/lib/python3.6 directory. I had to copy all the files there.

https://en.xdnf.cn/q/117859.html

Related Q&A

Matplotlib functions in tkinter

This is my first python project so I understand that this problem may seem a bit stupid. I am trying to create a Mandelbrot renderer. I am piecing code together from tutorials and code that I understan…

sudo su user -c with arguments not working

I am trying to execute command from python as another "user" with:command = "sudo su user -c player --standard=1 -o 2" subprocess.Popen(command.split(), shell=False, stdin=None, std…

Grouping data on column value

Hi I have data (in excel and text file as well) like C1 C2 C31 p a1 q b2 r c2 s dAnd I want the output like:C1 C2 C31 p,q a,b2 r,s c,dHow can I group the data…

Memory Error Python Processing Large File Line by Line

I am trying to concatenate model output files, the model run was broken up in 5 and each output corresponds to one of those partial run, due to the way the software outputs to file it start relabelling…

python assign literal value of a dictionary to key of another dictionary

I am trying to form a web payload for a particular request body but unable to get it right. What I need is to pass my body data as below data={file-data:{"key1": "3","key2&quo…

python regex findall span

I wanna find all thing between <span class=""> and </span> p = re.compile(<span class=\"\">(.*?)\</span>, re.IGNORECASE) text = re.findall(p, z)for exampl…

Why cant I view updates to a label while making an HTTP request in Python

I have this code :def on_btn_login_clicked(self, widget):email = self.log_email.get_text()passw = self.log_pass.get_text()self.lbl_status.set_text("Connecting ...")params = urllib.urlencode({…

plotting multiple graph from a csv file and output to a single pdf/svg

I have some csv data in the following format.Ln Dr Tag Lab 0:01 0:02 0:03 0:04 0:05 0:06 0:07 0:08 0:09 L0 St vT 4R 0 0 0 0 0 0…

parallel python: just run function n times [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 9…

how to specify the partition for mapPartition in spark

What I would like to do is compute each list separately so for example if I have 5 list ([1,2,3,4,5,6],[2,3,4,5,6],[3,4,5,6],[4,5,6],[5,6]) and I would like to get the 5 lists without the 6 I would do …