4

This is the python script will do. The question is how to call the external cmd file within the function?

  • Read a CSV file in the directory.
  • If the content in 6th column is equal to 'approved', then calls an external windows script 'TransferProd.cmd'

.

def readCSV(x):
    #csvContents is a list in the global scope that will contain lists of the  
    #items on each line of the specified CSV file
    try:
        global csvContents
        file = open(csvDir + x + '.csv', 'r')      #Opens the CSV file
        csvContents = file.read().splitlines()     #Appends each line of the CSV file to csvContents
        #----------------------------------------------------------------------
        #This takes each item in csvContents and splits it at "," into a list.
        #The list created replaces the item in csvContents
        for y in range(0,len(csvContents)):
            csvContents[y] = csvContents[y].lower().split(',')
        if csvContents[y][6] == 'approved':
            ***CALL TransferProd.cmd***
            file.close()
        return
    except Exception as error:
        log(logFile, 'An error has occurred in the readCSV function: ' + str(error))
        raise
joaquin
  • 82,968
  • 29
  • 138
  • 152
DIY Believer
  • 41
  • 2
  • 3
  • There are many solutions. Look at some questions on SO like http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python and also look at http://www.doughellmann.com/PyMOTW/subprocess/ – pyfunc Dec 06 '11 at 21:48

3 Answers3

4

Take a look at the subprocess module.

import subprocess
p = subprocess.Popen(['TransferProd.cmd'])

You can specify where you want output/errors to go (directly to a file or to a file-like object), pipe in input, etc.

Snago
  • 73
  • 5
1
import os
os.system('TransferProd.cmd')

This works in both unix/windows flavors as it send the commands to the shell. There are some variations in returned values though! Check here.

user1076371
  • 161
  • 6
  • How to specify the directory path for the TransferProd.cmd? Can os.chdir(cmdDir) or directly pass it in the code? – DIY Believer Dec 07 '11 at 14:28
  • 1
    I'd try to stay away from os.system. Unless you're using hardcoded strings, your program can be very susceptible to injection. Example: `os.system('./somescript' + filename)` and the input provided is `file.txt; rm -rf ~`. It is useful if it's just a short little burst of a programming script, though, no denying that. – Alyssa Haroldsen Nov 17 '12 at 09:30
0
  1. If you don't need output of the command you could use: os.system(cmd)
  2. The better solution is to use:

    from subprocess import Popen, PIPE
    proc = Popen(cmd, shell = True, close_fds = True)
    stdout, stderr = proc.communicate()
    
ILYA Khlopotov
  • 705
  • 3
  • 5