简体   繁体   English

如何在python脚本中调用cmd文件

[英]How to call a cmd file within python script

This is the python script will do. 这是python脚本会做的。 The question is how to call the external cmd file within the function? 问题是如何在函数内调用外部cmd文件?

  • Read a CSV file in the directory. 读取目录中的CSV文件。
  • If the content in 6th column is equal to 'approved', then calls an external windows script 'TransferProd.cmd' 如果第6列中的内容等于'approved',则调用外部Windows脚本'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

Take a look at the subprocess module . subprocess模块

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. 您可以指定输出/错误的位置(直接指向文件或类似文件的对象),输入管道等。

import os
os.system('TransferProd.cmd')

This works in both unix/windows flavors as it send the commands to the shell. 这适用于unix / windows风格,因为它将命令发送到shell。 There are some variations in returned values though! 但是返回值有一些变化! Check here . 点击这里

  1. If you don't need output of the command you could use: os.system(cmd) 如果您不需要输出命令,可以使用: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() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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