2012-12-06 56 views
0

我的程序目前由2個.py文件組成。如何從python中的.py文件打開python中的.py文件?

我運行代碼的主要部分在pypy(這是更快),然後我打開第二個文件在Python中繪製我的數據使用matplotlib.pyplot

我有管理的使用打開:

subprocess.Popen(['C:\\python26\\python.exe ','main_plot.py',]) 
這將打開我的第二個文件

...

import matplotlib.pyplot as pyplot 
def plot_function(NUMBER): 
    '''some code that uses the argument NUMBER''' 
    pyplot.figure() 
    ---plot some data--- 
    pyplot.show() 

不過,我想可以將參數傳遞給打開的plot_function在python中。那可能嗎?

回答

2

是的,POPEN構造函數採用長度爲n的列表。 See the note here.所以只需添加參數main_plot.py到您的列表:

subprocess.Popen(['C:\\python26\\python.exe ','main_plot.py','-n',1234]) 

EDIT(到您的編輯迴應):

您需要修改main_plot.py接受命令行參數來調用你的功能。這將做到這一點:

import matplotlib.pyplot as pyplot 
def plot_function(NUMBER): 
    '''some code that uses the argument NUMBER''' 
    pyplot.figure() 
    ---plot some data--- 
    pyplot.show() 

import argparse 
if __name__=="__main__": 
    argp=argparse.ArgumentParser("plot my function") 
    argp.add_argument("-n","--number",type=int,default=0,required=True,help="some argument NUMBER, change type and default accordingly") 
    args=argp.parse_args() 
    plot_function(args.number) 
+0

我真正想要做的是傳遞一個數字到我的繪圖文件中的函數。是否有可能做到這一點? '-f'用於什麼? – user1696811

+0

我更新了我的答案 –

+0

謝謝,這正是我所需要的! (我不知道'dbo = DB()'做了什麼,它給了我一個錯誤,所以我刪除它,程序似乎運行良好) – user1696811

0

最簡單的方法是os.system("main_plot.py arg")