子流程模块工作但不完全正常工作

时间:2014-07-04 03:08:36

标签: python subprocess maya

我正在尝试将os.system替换为子进程模块(引用here),但是它似乎有用(在脚本编辑器中显示结果),但它实际上不起作用。< / p>

def convert_text(inImg, outImg, texImg):
    if not os.path.exists(texImg):
        Image.open(inImg).save(outImg)
        #os.system('/apps/Linux64/prman-18.0/bin/txmake ' + outImg + ' ' + texImg)
        subprocess.Popen("/apps/Linux64/prman-18.0/bin/txmake" + outImg + " " + texImg, shell = True)
        os.remove(outImg)
        print "Done converting " + inImg

上面的代码应该查找任何图像文件,将其转换为.tif,然后是.tex。虽然结果可能表示Done converting /user_data/texture/testTexture_01.tga,但实际上在目录中找不到任何.tex文件。 (应该有.tex文件位于/ user_data / texture,图像文件所在的位置)

我也尝试将其写为subprocess.Popen('/apps/Linux64/prman-18.0/bin/txmake %s %s'% (outImg, texImg), shell = True),但它无法正常工作。

编辑:我正在Maya中运行以下代码,因为我正在该软件中实现该代码

我在某些方面做错了吗?

3 个答案:

答案 0 :(得分:3)

subprocess.Popen获取参数列表。即试试:

subprocess.Popen(["/apps/Linux64/prman-18.0/bin/txmake", outImg, texImg])

更新:已移除shell=True

答案 1 :(得分:1)

正如@suhail所说,Popen获取了一个参数列表,但是(截至目前)他的示例代码是错误的。它应该是这样的:

#os.system('/apps/Linux64/prman-18.0/bin/txmake ' + outImg + ' ' + texImg)
subprocess.Popen(["/apps/Linux64/prman-18.0/bin/txmake", outImg, texImg])

除非您确认outImg和texImg没有对shell有特殊含义的字符(引号,空格不使用shell = True >,星号等)。对于shell = True,这些字符将由shell处理,结果可能不是您所期望的。你想要的是shell = False(这是默认值),所以带有引号,空格等的文件名在传递给shell之前会被正确地反斜杠转义。

更新:您可能希望使用subprocess.call(),而不是subprocess.Popen()。请参阅the subprocess module documentationcall()将等待命令完成,然后返回整数返回码(如果没有错误,则返回0)。您应捕获该返回代码并对其进行测试,然后仅在没有错误时删除outImg。 。E.g,:

def convert_text(inImg, outImg, texImg):
    if not os.path.exists(texImg):
        Image.open(inImg).save(outImg)
        #os.system('/apps/Linux64/prman-18.0/bin/txmake ' + outImg + ' ' + texImg)
        retcode = subprocess.call("/apps/Linux64/prman-18.0/bin/txmake", outImg, texImg)
        if (retcode == 0):
            os.remove(outImg)
        else:
            print "txmake returned error code " + str(retcode)
        print "Done converting " + inImg

阅读文档,详细了解如何使用call()

答案 2 :(得分:1)

Popen是非阻塞的,因此在调用返回时它实际上并不完整。因为您在outImg调用开始后立即删除了Popen,所以命令可能会失败。请改用subprocess.call,这将阻塞直到命令完成:

subprocess.call(["/apps/Linux64/prman-18.0/bin/txmake", outImg, texImg]) 
相关问题