如何从另一个Python脚本中执行带参数的Python脚本文件
我的问题是,我想从一个Python文件里面执行另一个Python文件,并传递一个参数,以便获取返回的值……
我不知道我是否解释得清楚……
举个例子:
我在命令行中执行这个:
getCameras.py "path_to_the_scene"
然后这会返回一个摄像头的列表……
那么我该如何从另一个脚本调用这个脚本(包括参数)呢???
我一直在尝试自己搞明白,看看这里的其他问题,但我还是没弄明白,我应该使用execfile()函数吗??具体该怎么做??
谢谢你们提前帮助像我这样的新手!!
好的,经过查看你们的回答,我需要编辑我的问题,让它更简洁,因为我不理解某些回答(抱歉,正如我所说,我是个新手!!!):
我有两个脚本,getMayaCameras.py
和doRender.py
,还有一个renderUI.py
,它在图形界面中实现了前两个脚本。
getMayaCameras.py
和doRender.py
都是可以直接从系统命令行执行的脚本,只需添加一个参数(或者在doRender.py
中是标志),如果可能的话,我希望仍然保留这个功能,这样我可以选择是执行图形界面还是直接从命令行执行脚本。
我已经对它们做了一些修改,使它们可以通过renderUI.py
导入工作,但现在它们自己不能工作了。
是否可以让这些脚本独立工作,同时又能从另一个脚本调用它们?具体该怎么做?你之前提到的“将逻辑与命令行参数处理分开”听起来不错,但我不知道该如何在我的脚本中实现(我试过,但没有成功)。
这就是我在这里发布原始代码的原因,你可以随意批评和/或纠正代码,告诉我该如何做才能让脚本正常工作。
#!/usr/bin/env python
import re,sys
if len(sys.argv) != 2:
print 'usage : getMayaCameras.py <path_to_originFile> \nYou must specify the path to the origin file as the first arg'
sys.exit(1)
def getMayaCameras(filename = sys.argv[1]):
try:
openedFile = open(filename, 'r')
except Exception:
print "This file doesn't exist or can't be read from"
import sys
sys.exit(1)
cameras = []
for line in openedFile:
cameraPattern = re.compile("createNode camera")
cameraTest = cameraPattern.search(line)
if cameraTest:
cameraNamePattern = re.compile("-p[\s]+\"(.+)\"")
cameraNameTest = cameraNamePattern.search(line)
name = cameraNameTest.group(1)
cameras.append(name)
openedFile.close()
return cameras
getMayaCameras()
7 个回答
还有一种可能更好的方法来替代使用 os.system()
,那就是使用 subprocess
模块。这个模块是为了取代 os.system()
以及其他几个稍微旧一点的模块而设计的。假设你有一个程序,想要通过一个主程序来调用它:
import argparse
# Initialize argument parse object
parser = argparse.ArgumentParser()
# This would be an argument you could pass in from command line
parser.add_argument('-o', action='store', dest='o', type=str, required=True,
default='hello world')
# Parse the arguments
inargs = parser.parse_args()
arg_str = inargs.o
# print the command line string you passed (default is "hello world")
print(arg_str)
从主程序中使用上面的程序和 subprocess
的方式看起来是这样的:
import subprocess
# run your program and collect the string output
cmd = "python your_program.py -o THIS STRING WILL PRINT"
out_str = subprocess.check_output(cmd, shell=True)
# See if it works.
print(out_str)
最终,这段代码会打印出 "THIS STRING WILL PRINT"
,这就是你传给我称之为主程序的内容。subprocess
有很多选项,使用它的好处是,你写的程序可以在不同的系统上运行而不受限制。想了解更多,可以查看 subprocess
和 argparse
的文档。
首先,我同意其他人的看法,你应该修改你的代码,把逻辑和命令行参数的处理分开。
但是在使用其他库的时候,如果你不想去修改它们,知道怎么在Python里面做类似的命令行操作还是很有用的。
解决办法就是使用 os.system(command)
至少在Windows上,它会打开一个控制台并执行这个命令,就像你在命令提示符里输入的一样。
import os
os.system('getCameras.py "path_to_the_scene" ')
最好的建议是不要这样做。你可以把你的 getCameras.py 文件写成下面这样:
import stuff1
import stuff2
import sys
def main(arg1, arg2):
# do whatever and return 0 for success and an
# integer x, 1 <= x <= 256 for failure
if __name__=='__main__':
sys.exit(main(sys.argv[1], sys.argv[2]))
然后在你的其他脚本中,你可以这样做:
import getCamera
getCamera.main(arg1, arg2)
或者你也可以调用 getCamera.py 中的其他函数。