[英]How do you call a python file that requires a command line argument from within another python file?
例如,我有兩個python文件,分別為'test1.py'
和'test2.py'
。 我想import test2
到test1
,以便當我運行test1
,它也運行test2
。
但是,為了正常運行, test2
需要輸入參數。 通常,當我從test1
外部運行test2
時,只需在command line
的文件調用之后鍵入參數。 從test1
內調用test2
時,我該如何做到這一點?
根據編輯test2.py的能力,有兩個選項:
在test1.py文件中:
from test2 import test2class
t2c = test2class(neededArgumetGoHere)
t2c.main()
在test2.py文件中:
class test2class:
def __init__(self, neededArgumetGoHere):
self.myNeededArgument = neededArgumetGoHere
def main(self):
# do stuff here
pass
# to run it from console like a simple script use
if __name__ == "__main__":
t2c = test2class(neededArgumetGoHere)
t2c.main()
test1.py
from subprocess import call
call(['path/to/python','test2.py','neededArgumetGoHere'])
假設您可以定義自己的test1和test2,並且可以使用argparse很好(無論如何,這是一個好主意):
使用argparse的好處是,您可以讓test2定義一堆不需要test1擔心的默認參數值。 並且,從某種意義上說,您具有用於test2調用的文檔化接口。
抄襲https://docs.python.org/2/howto/argparse.html
test2.py
import argparse
def get_parser():
"separate out parser definition in its own function"
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number")
return parser
def main(args):
"define a main as the test1=>test2 entry point"
print (int(args.square)**2)
if __name__ == '__main__':
"standard test2 from command line call"
parser = get_parser()
args = parser.parse_args()
main(args)
奧黛麗:探索jluc $ python test2.py 3
9
test1.py
import test2
import sys
#ask test2 for its parser
parser = test2.get_parser()
try:
#you can use sys.argv here if you want
square = sys.argv[1]
except IndexError:
#argparse expects strings, not int
square = "5"
#parse the args for test2 based on what test1 wants to do
#by default parse_args uses sys.argv, but you can provide a list
#of strings yourself.
args = parser.parse_args([square])
#call test2 with the parsed args
test2.main(args)
奧黛麗:探索jluc $ python test1.py 6
36
奧黛麗:探索jluc $ python test1.py
25
您可以使用子流程模塊中的call或popen方法。
from subprocess import call, Popen
Call(file, args)
Popen(file args)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.