'python program'.count('p')_Python,在p中运行命令行工具

使用multiprocessing模块中的Pool对象。然后可以使用例如Pool.map()来执行并行处理。一个例子是我的markphotos脚本(见下文),其中一个函数被多次调用,并行于每个处理一张图片。#! /usr/bin/env python

# -*- coding: utf-8 -*-

# Adds my copyright notice to photos.

#

# Author: R.F. Smith

# $Date: 2012-10-28 17:00:24 +0100 $

#

# To the extent possible under law, Roland Smith has waived all copyright and

# related or neighboring rights to markphotos.py. This work is published from

# the Netherlands. See http://creativecommons.org/publicdomain/zero/1.0/

import sys

import subprocess

from multiprocessing import Pool, Lock

from os import utime, devnull

import os.path

from time import mktime

globallock = Lock()

def processfile(name):

"""Adds copyright notice to the file.

Arguments:

name -- file to modify

"""

args = ['exiftool', '-CreateDate', name]

createdate = subprocess.check_output(args)

fields = createdate.split(":") #pylint: disable=E1103

year = int(fields[1])

cr = "R.F. Smith http://rsmith.home.xs4all.nl/"

cmt = "Copyright © {} {}".format(year, cr)

args = ['exiftool', '-Copyright="Copyright (C) {} {}"'.format(year, cr),

'-Comment="{}"'.format(cmt), '-overwrite_original', '-q', name]

rv = subprocess.call(args)

modtime = int(mktime((year, int(fields[2]), int(fields[3][:2]),

int(fields[3][3:]), int(fields[4]), int(fields[5]),

0,0,-1)))

utime(name, (modtime, modtime))

globallock.acquire()

if rv == 0:

print "File '{}' processed.".format(name)

else:

print "Error when processing file '{}'".format(name)

globallock.release()

def checkfor(args):

"""Make sure that a program necessary for using this script is

available.

Arguments:

args -- list of commands to pass to subprocess.call.

"""

if isinstance(args, str):

args = args.split()

try:

with open(devnull, 'w') as f:

subprocess.call(args, stderr=subprocess.STDOUT, stdout=f)

except:

print "Required program '{}' not found! exiting.".format(args[0])

sys.exit(1)

def main(argv):

"""Main program.

Arguments:

argv -- command line arguments

"""

if len(argv) == 1:

binary = os.path.basename(argv[0])

print "Usage: {} [file ...]".format(binary)

sys.exit(0)

checkfor(['exiftool', '-ver'])

p = Pool()

p.map(processfile, argv[1:])

p.close()

if __name__ == '__main__':

main(sys.argv)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值