简体   繁体   中英

Python: How to import zip from a different directory

I am deploying some python scripts as Azure Web Jobs and ran into an issue with importing some shared modules (in the form of zip files). Everything works fine if I copy the zip files to the same directory as the script file. But if I move the zip files to a different directory, things stop working.

Now for the specifics.

1) This works

Directory structure:

App_data
  jobs
    continuous
      firstjob
        azure.zip
        job1.py
      secondjob
        azure.zip
        job2.py

In job1.py (and job2.py), I add the following code:

  sys.path.insert(0, 'azure.zip')
  from azure.storage.blob import *

1) This does NOT work

Directory structure:

App_data
  pylib
    azure.zip
  jobs
    continuous
      firstjob
        job1.py
      secondjob
        job2.py

In job1.py (and job2.py), I add the following code: # Azure places the scripts one level lower than it appears in the solution, hence the extra '..'!

  lib_path = os.path.realpath('..\..\..\pylib')
  sys.path.insert(0, os.path.join(lib_path, 'azure.zip'))
  # I verified by printing sys.path that the correct path is added for azure.zip
  from azure.storage.blob import *

This gives an import error. Any ideas?

I tested you code above in my local using pycharm. The second code can also work well. I am using python3.5.0. I am not sure why the error appears. Maybe the issue of python version in Azure. Hope this will help others.

I tried to find out the reason of this issue for the second job via run the code snippet below.

import os
real_path = os.path.realpath('.')
print real_path

The result of variable real_path of the current webjob path is D:\\local\\Temp\\jobs\\continuous\\second\\<a generated name like vjvunhav.obn>\\ .

Note

Please see the section Logging of Wiki-Doc Web Jobs to know the path of WebJobs - Console.Out and Console.Error .

So you can try to directly use the absolute path /Home/site/wwwroot/App_Data/pylib/azure.zip in the code below.

import sys
sys.path.insert(0, '/Home/site/wwwroot/App_Data/pylib/azure.zip')

Best Regards.

When the azure webjob is executed, the content of the directory is copied in a temp subdirectory of your website "data" folder (at the root /data).

If you put the zip file in the same folder than your Python script, it will be copied too. If not, you need to use the absolute path "/site/wwwroot/mysite/App_data/pylib/"

That should work !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM