如何使用另一个python脚本文件中的参数执行python脚本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4230725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:50:56  来源:igfitidea点击:

how to execute a python script file with an argument from inside another python script file

python

提问by user497457

my problem is that I want to execute a python file with an argument from inside another python file to get the returned values....

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

I don't know if I've explained it well...

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

example:

例子:

from the shell I execute this:

从外壳我执行这个:

          getCameras.py "path_to_the_scene"

and this return me a list of cameras....

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

so how can I call this script (including the argument) from another script ???

那么我如何从另一个脚本调用这个脚本(包括参数)???

I've been trying to figure it out by myself by reading some other questions here , but I didn't get it well, should I use the execfile() function?? how exactly??

我一直试图通过阅读这里的其他一些问题来自己弄清楚,但我没有弄明白,我应该使用 execfile() 函数吗?具体如何??

Thanks in advance for helping a newbie like me!!

在此先感谢您帮助像我这样的新手!!

Ok, after take a look at your answers, I have to edit my question to make it more concise and because I don't understand some answers(sorry, like I said I'm a newbie!!!):

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

Well, I have this 2 scripts "getMayaCameras.py" and "doRender.py" and one more called "renderUI.py" that implements the first 2 scripts in a GUI.

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

"getMayaCameras.py" and "doRender.py" are both scipts that you can execute directly from the system shell by adding an argument ( or flags, in the "doRender.py" case) and, If it is possible, I want to still having this posibility so I can choose between execute the UI or execute the script dirctly from the shell

“getMayaCameras.py”和“doRender.py”都是您可以通过添加参数(或标志,在“doRender.py”案例中)直接从系统外壳执行的脚本,如果可能,我想仍然有这种可能性,所以我可以在执行 UI 或直接从 shell 执行脚本之间进行选择

I've made already some modifications for them to work by importing them from the "renderUI.py" script but now they don't work by themselves....

我已经通过从“renderUI.py”脚本导入它们为它们进行了一些修改,但现在它们不能自己工作......

So is possible to have this scripts working by themselves and still having the possiblity of calling them from another script? how exactly? This "separating the logic from the command line argument handling"that you told me before sounds good to me but I don't know how to implement it on my script ( I tried but without succes) ....

那么是否可以让这些脚本自己工作,并且仍然可以从另一个脚本调用它们?究竟如何?您之前告诉我的这种 “将逻辑与命令行参数处理分离”对我来说听起来不错,但我不知道如何在我的脚本中实现它(我尝试过但没有成功)......

That's why I'm posting here the original code for you to see how I made it, feel free both to make critics and/or correct the code to explain me how should I make it for the script to work properly...

这就是为什么我在这里发布原始代码供您查看我是如何制作的,请随时提出批评和/或更正代码以解释我应该如何使其脚本正常工作......

#!/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()

Thanks again,

再次感谢,

David

大卫

采纳答案by aaronasterling

The best answer is don't. Write your getCameras.py as

最好的答案是不要。将您的 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]))

From your other script, you can then do

从你的其他脚本,你可以做

import getCamera

getCamera.main(arg1, arg2)

or call any other functions in getCamera.py

或调用 getCamera.py 中的任何其他函数

回答by Ignacio Vazquez-Abrams

execfile()runs one script within the other, which is not what you want. The subprocessmodule can be used to run another instance of the Python interpreter, but what you should do is look at getCameras.pyand see if there's some function you can invoke after importing it.

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

回答by Ponkadoodle

First off, I agree with others that you should edit your code to separate the logic from the command line argument handling.

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

But in cases where you're using other libraries and don't want to mess around editing them, it's still useful to know how to do equivalent command line stuff from within Python.
The solution is os.system(command)
Atleast on Windows, it brings up a console and executes the command, just the same way as if you had entered it into the command prompt.

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

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

回答by maguschen

I suggest you reorganized your getCameras.py, wrap the get camera list code in a method called get_cameras(). Then you can call this method in other python scripts.

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

getCameras.py

获取相机文件

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

How to use: other.py

使用方法:other.py

import getCameras
camera_list = getCameras.get_cameras()

回答by user2645976

Another way that may be preferable to using os.system()would be to use the subprocessmodule which was invented to replace os.system()along with a couple of other slightly older modules. With the following program being the one you want to call with some master program:

另一种可能更适合使用的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)

Using the above program with subproccess from a master program would would look like this:

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

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)

At the end of the day this will print "THIS STRING WILL PRINT", which is the one you passed into what I called the master program. subprocesshas lots of options but it is worth using because if you use it write your programs will be system independent. See the documentation for subprocess, and argparse.

在一天结束时,这将打印"THIS STRING WILL PRINT",这是您传递给我所谓的主程序的那个。subprocess有很多选择,但值得使用,因为如果您使用它,您的程序将与系统无关。请参阅subprocess, 和的文档argparse