Как использовать Popen в Windows для вызова внешнего скрипта .py и ожидания его завершения - PullRequest
1 голос
/ 12 ноября 2008

Вы когда-нибудь пробовали этот отзыв, вызывая внешний скрипт zip.py для работы? Мой CGITB не показывает никаких сообщений об ошибках. Он просто не вызывал внешний скрипт .py для работы. Он просто перескочил, чтобы изливаться. Буду признателен, если вы поможете мне сделать этот zip.py вызываемым в feedback.py.

С уважением. Дэвид

#**********************************************************************
# Description:
#    Zips the contents of a folder.
# Parameters:
#   0 - Input folder.
#   1 - Output zip file. It is assumed that the user added the .zip 
#       extension.  
#**********************************************************************

# Import modules and create the geoprocessor
#
import sys, zipfile, arcgisscripting, os, traceback
gp = arcgisscripting.create()

# Function for zipping files.  If keep is true, the folder, along with 
#  all its contents, will be written to the zip file.  If false, only 
#  the contents of the input folder will be written to the zip file - 
#  the input folder name will not appear in the zip file.
#
def zipws(path, zip, keep):
    path = os.path.normpath(path)
    # os.walk visits every subdirectory, returning a 3-tuple
    #  of directory name, subdirectories in it, and filenames
    #  in it.
    #
    for (dirpath, dirnames, filenames) in os.walk(path):
        # Iterate over every filename
        #
        for file in filenames:
            # Ignore .lock files
            #
            if not file.endswith('.lock'):
                gp.AddMessage("Adding %s..." % os.path.join(path, dirpath, file))
                try:
                    if keep:
                        zip.write(os.path.join(dirpath, file),
                        os.path.join(os.path.basename(path),
                        os.path.join(dirpath, file)[len(path)+len(os.sep):]))
                    else:
                        zip.write(os.path.join(dirpath, file),            
                        os.path.join(dirpath[len(path):], file)) 

                except Exception, e:
                    gp.AddWarning("    Error adding %s: %s" % (file, e))

    return None

if __name__ == '__main__':
    try:
        # Get the tool parameter values
        #
        infolder = gp.GetParameterAsText(0)
        outfile = gp.GetParameterAsText(1)      

        # Create the zip file for writing compressed data. In some rare
        #  instances, the ZIP_DEFLATED constant may be unavailable and
        #  the ZIP_STORED constant is used instead.  When ZIP_STORED is
        #  used, the zip file does not contain compressed data, resulting
        #  in large zip files. 
        #
        try:
                zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED)
                zipws(infolder, zip, True)
                zip.close()
        except RuntimeError:
                # Delete zip file if exists
                #
                if os.path.exists(outfile):
                        os.unlink(outfile)
                zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED)
                zipws(infolder, zip, True)
                zip.close()
                gp.AddWarning("    Unable to compress zip file contents.")

        gp.AddMessage("Zip file created successfully")

    except:
        # Return any python specific errors as well as any errors from the geoprocessor
        #
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + 
                "\nError Info:\n    " +                 str(sys.exc_type) + 
                ": " + str(sys.exc_value) + "\n"
        gp.AddError(pymsg)

        msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n"
        gp.AddError(msgs)

Ответы [ 2 ]

1 голос
/ 12 ноября 2008
  • zip() - это встроенная функция в Python. Поэтому плохая практика - использовать zip в качестве имени переменной. zip_ можно использовать вместо.

  • execfile() функция читает и выполняет скрипт Python.

  • Вероятно, вам действительно нужен import zip_ в feedback.py вместо execfile().

0 голосов
/ 12 ноября 2008

Yay ArcGIS.

Просто чтобы уточнить, как вы пытаетесь вызвать этот скрипт с помощью popen, вы можете опубликовать какой-нибудь код?

Если вы вызываете этот скрипт через другой скрипт в среде ArcGIS, то дело в том, что когда вы используете Popen, скрипт не будет вызываться в среде ArcGIS, вместо этого он будет вызываться в окнах. Таким образом, вы потеряете весь реальный контроль над ним.

Также просто еще один комментарий ArcGIS: вы никогда не инициализируете лицензию для геопроцессора.

Мое предложение реорганизовать ваш код в функцию модуля, которая просто пытается заархивировать файлы, если не удается распечатать сообщение в ArcGIS.

Если вы хотите опубликовать, как вы это называете, и как это выполняется.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...