[英]How to execute a python script file with an argument from inside another python script file
我的問題是我想使用另一個 python 文件中的參數執行 python 文件以獲取返回值....
不知道我解釋的好不好...
例子:
從 shell 我執行這個:
getCameras.py "path_to_the_scene"
這給我一個相機列表....
那么如何從另一個腳本調用這個腳本(包括參數)???
我一直試圖通過在這里閱讀其他一些問題來自己解決這個問題,但我沒有搞清楚,我應該使用 execfile() function 嗎? 到底怎么樣??
在此先感謝您幫助像我這樣的新手!!
好的,在看了你的答案之后,我必須編輯我的問題以使其更簡潔,因為我不明白一些答案(對不起,就像我說我是新手:!!):
我有兩個腳本getMayaCameras.py
和doRender.py
,還有一個renderUI.py
,它在 GUI 中實現前兩個腳本。
getMayaCameras.py
和doRender.py
都是您可以通過添加參數(或標志,在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()
最好的答案是不要 。 把你的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中的任何其他函數
首先,我同意其他人的意見,你應該編輯你的代碼,將邏輯與命令行參數處理分開。
但是如果您正在使用其他庫並且不想編輯它們,那么知道如何從Python中執行等效的命令行工作仍然很有用。
解決方案是os.system(命令)
在Windows上,它會調出一個控制台並執行命令,就像您在命令提示符中輸入它一樣。
import os
os.system('getCameras.py "path_to_the_scene" ')
另一種可能比使用os.system()
更好的方法是使用發明的subprocess
os.system()
模塊來替換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
。
execfile()
在另一個腳本中運行一個腳本,這不是你想要的。 subprocess
模塊可用於運行Python解釋器的另一個實例,但你應該做的是查看getCameras.py
並查看是否有一些函數可以在導入后調用。
我建議你重新組織你的getCameras.py,將get相機列表代碼包裝在一個名為get_cameras()的方法中。 然后你可以在其他python腳本中調用這個方法。
getCameras.py
def get_cameras():
bulabula...
if __name__ == '__main__':
return get_cameras()
使用方法:other.py
import getCameras
camera_list = getCameras.get_cameras()
要回答你的問題(那么我怎么能從另一個腳本調用這個腳本(包括參數)??? )簡單地:
您可以使用 runfile() 命令從另一個腳本連同其參數一起運行腳本,如下所示:
runfile("YourScript.py",args="Your_argument",wdir="Your working dir")
服務1.py:
import test1
test1.some_func(1,2)
測試1.py:
import sys
def some_func(arg1, arg2):
#all the code in def has to be indented, exit 0 if no error, exit code if error
# do something
print arg2
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func(argv[1], argv[2])
跑:
python service1.py
python test1.py 3 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.