【问题标题】:how to execute a python script file with an argument from inside another python script file如何使用另一个 python 脚本文件中的参数执行 python 脚本文件
【发布时间】:2010-11-20 01:19:50
【问题描述】:

我的问题是我想从另一个 python 文件中执行一个带有参数的 python 文件以获取返回值....

不知道我解释的好不好……

示例:

我从 shell 执行这个:

          getCameras.py "path_to_the_scene"

这会返回给我一个相机列表....

那么我怎样才能从另一个脚本调用这个脚本(包括参数)???

我一直试图通过阅读这里的其他一些问题来自己解决这个问题,但我没有搞清楚,我应该使用 execfile() 函数吗?具体怎么样?

提前感谢您帮助像我这样的新手!

好的,在看了你的答案之后,我必须编辑我的问题以使其更简洁,因为我不明白一些答案(对不起,就像我说我是新手!!!):

嗯,我有这 2 个脚本“getMayaCameras.py”和“doRender.py”,还有一个名为“renderUI.py”的脚本在 GUI 中实现了前 2 个脚本。

“getMayaCameras.py”和“doRender.py”都是 scipts,您可以通过添加参数(或标志,在“doRender.py”情况下)直接从系统 shell 执行,如果可能的话,我希望仍然拥有这种可能性,因此我可以选择执行 UI 或直接从 shell 执行脚本

我已经对它们进行了一些修改,通过从“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()

再次感谢,

大卫

【问题讨论】:

    标签: python


    【解决方案1】:

    最好的答案是不要。把你的 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 中的任何其他函数

    【讨论】:

    • 我不太明白,这样你仍然可以从shell调用带有args的脚本吗?...无论如何我试图在我的脚本中实现它但没有成功,请问你能用我留在这里的脚本来做吗,所以我可以用它作为例子吗?
    【解决方案2】:

    首先,我同意其他人的观点,即您应该编辑代码以将逻辑与命令行参数处理分开。

    但是,如果您正在使用其他库并且不想乱七八糟地编辑它们,那么了解如何在 Python 中执行等效的命令行操作仍然很有用。
    解决方案是 os.system(command)
    至少在 Windows 上,它会打开一个控制台并执行命令,就像您在命令提示符中输入它一样。

    import os
    os.system('getCameras.py "path_to_the_scene" ')
    

    【讨论】:

    • 感谢您的回答,但我无法让它工作,至少如果我做类似 camera = os.system('getCameras.py "path_to_the_scene" ') 之类的事情......它没有得到返回值
    • 我通过使用以下os.system('python getCameras.py "path_to_the_scene"') 使其工作。我自己的脚本实际上包含一个输出:os.system('python sample.py &gt;&gt; out.txt') 并且运行良好
    【解决方案3】:

    另一种可能比使用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)
    

    将上述程序与主程序的子进程一起使用将如下所示:

    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 的文档。

    【讨论】:

      【解决方案4】:

      execfile() 在另一个脚本中运行一个脚本,这不是您想要的。 subprocess 模块可用于运行 Python 解释器的另一个实例,但您应该查看 getCameras.py 并查看导入后是否可以调用某些函数。

      【讨论】:

        【解决方案5】:

        我建议您重新组织您的 getCameras.py,将获取相机列表代码包装在一个名为 get_cameras() 的方法中。然后就可以在其他python脚本中调用这个方法了。

        getCameras.py

        def get_cameras():
        bulabula...
        if __name__ == '__main__':
        return get_cameras()
        

        使用方法:other.py

        import getCameras
        camera_list = getCameras.get_cameras()
        

        【讨论】:

          猜你喜欢
          • 2012-09-07
          • 1970-01-01
          • 2022-01-07
          • 2021-07-21
          • 1970-01-01
          • 1970-01-01
          • 2014-03-02
          • 2018-04-13
          • 1970-01-01
          相关资源
          最近更新 更多