需要一个脚本来迭代文件并执行命令

2024-04-28 22:16:54 发布

您现在位置:Python中文网/ 问答频道 /正文

请原谅我,我以前没有用过python,我正试图尽快完成一些渲染,并因此停止了我的工作。在

我将.ifd文件输出到网络驱动器(Z:),它们存储在一个文件夹结构中,比如

Z:  
 - \0001 
 - \0002 
 - \0003

我需要在一个文件夹中迭代ifd文件,但是文件的数量不是静态的,所以还需要有一个可定义的范围(1-300,1-2500,等等)。因此,该脚本必须能够为开始和结束范围附加两个参数。在

在每次迭代中,它使用这个语句执行一个叫做“mantra”的东西

^{pr2}$

我在网上找到了一个脚本,它应该做类似的事情

import sys, os

#import command line args
args = sys.argv

# get args as string
szEndRange = args.pop()
szStartRange = args.pop()

#convert args to int
nStartRange = int(szStartRange, 10);
nEndRange = int(szEndRange, 10);
nOrd = len(szStartRange);

#generate ID range
arVals = range(nStartRange, nEndRange+1);


for nID in arVals:
   szFormat = 'mantra -V a -f testDebris.%%(id)0%(nOrd)dd.ifd' % {"nOrd": nOrd};
   line = szFormat % {"id": nID};
   os.system(line);

我的问题是我不能让它工作。它似乎在迭代,并做一些事情-但它看起来只是把ifd吐到某个不同的文件夹中。在

TLDR

我需要一个脚本,其中至少有两个论点

  • 开始帧
  • 结束帧

然后从这些文件中创建一个frameRange,然后用于迭代执行以下命令的所有ifd文件

  • 咒语-f文件名.currentframe.ifd文件名.currentFrame.png在

如果我能指定文件名、文件目录和输出目录,那也太好了。我尝试过手动操作,但一定有一些惯例我不知道,因为当我尝试(在冒号处停止)时,它会出现错误。在

如果有人能帮我接电话或给我指点方向那就太好了。我知道我应该尝试学习python,但我对渲染无能为力,需要帮助。在


Tags: 文件import脚本文件夹os文件名sysline
3条回答
import os, subprocess, sys

if len(sys.argv) != 3:
    print('Must have 2 arguments!')
    print('Correct usage is "python answer.py input_dir output_dir" ')
    exit()

input_dir = sys.argv[1]
output_dir = sys.argv[2]
input_file_extension = '.txt'
cmd = 'currentframe'

# iterate over the contents of the directory
for f in os.listdir(input_dir):
    # index of last period in string
    fi = f.rfind('.')
    # separate filename from extension
    file_name = f[:fi]
    file_ext = f[fi:]
    # create args
    input_str = '%s.%s.ifd' % (os.path.join(input_dir, file_name), cmd)
    output_str =  '%s.%s.png' % (os.path.join(output_dir + file_name), cmd)
    cli_args = ['mantra', '-f', input_str, output_str]
    #call function
    if subprocess.call(cli_args, shell=True):
        print('An error has occurred with command "%s"' % ' '.join(cli_args))

这应该足够你使用当前或稍加修改。在

一点帮助建立指挥部。在

for nID in arVals:
   command = 'mantra -V a -f '
   infile = '{0}.{1:04d}.ifd '.format(filename, id)
   outfile = '{0}.{1:04d}.png '.format(filename, id)              
   os.system(command + infile + outfile);

一定要像@logic推荐的那样使用os.walk或{}

^{pr2}$

不必特别输入起始和结束范围,您只需:

import os

path, dirs, files = os.walk("/Your/Path/Here").next()
nEndRange = len(files)

#generate ID range    
arVals = range(1, nEndRange+1);

命令os.walk()统计指定文件夹中的文件数。在

不过,获得所需输出的更简单方法如下:

^{pr2}$

因为os.listdir()遍历指定的目录,filename是该目录中的每个文件,所以您甚至不需要计算它们。在

相关问题 更多 >