2017-07-24 57 views
-2

我有以下代碼:如何訪問在函數中聲明的變量?

SCRIPT1

def encoder(input_file): 
    # a bunch of other code 
    # some more code 

    # path to output of above code 
    conv_output_file = os.path.join(input_file_gs, output_format) 
    subprocess.run(a terminal file conversion runs here) 

if __name__ == "__main__": 
    encoder("path/to/file") 

這是我嘗試導入以及如何將其設置爲SCRIPT2。

SCRIPT2

from script1 import encoder 
# some more code and imports 
# more code 
# Here is where I use the output_location variable to set the input_file variable in script 2 
input_file = encoder.conv_output_file 

我所試圖做的是另一種python3文件中使用的變量output_location。所以,我可以告訴SCRIPT2到哪裏尋找它嘗試沒有硬編碼處理文件

我每次運行該腳本雖然我得到以下錯誤:

NameError: name 'conv_output_file' is not defined 
+5

爲什麼你不能''在函數中返回conv_output_file'? – idjaw

+3

每種方法中的問題/錯誤是什麼?添加更多的代碼到目前爲止你已經嘗試 –

+0

@idjaw我已經試過這個,但我仍然得到不斷收到'conv_output_file沒有定義錯誤。「# – EliC

回答

-1

我想除了不返回變量或不將其聲明爲類變量,那麼您可能會犯另一個錯誤。

tell that 2nd script

你要好好import第一腳本到你的第二個腳本,並使用encoder函數作爲第一個腳本的屬性。

例如,將您的第一個腳本命名爲encoder_script。 在第二個腳本,

import encoder_script 
encoder_script.encode(filename) 
+0

介意解釋downvote? –

-1

我從你的描述得到的是,你想從另一個Python文件中的局部變量。

將其返回或使其成爲全局變量,然後導入它。


也許你在正確導入時遇到了一些困難。

讓這兩點明確:

  1. 你只能通過兩種方式導入包:包在PYTHONPATH或本地包。特別是,如果您想執行任何相關導入,請在包名稱前面添加.以指定要導入的包。
  2. 只有當目錄下有__init__.py時,Python解釋器纔會將目錄視爲包。
-1

你真的想用變量conv_output_file做什麼?如果您只想獲取conv_output_file綁定的值/對象,那麼最好使用return語句。或者如果你想訪問變量並在變量上做更多的事情,即修改它,那麼你可以使用全局訪問變量conv_output_file。

def encoder(input_file): 
    # a bunch of other code 
    # some more code 

    # path to output of above code 
    global conv_output_file 
    conv_output_file = os.path.join(input_file_gs, output_format) 

您現在可以從第二個腳本firstscript.conv_output_file調用該函數firstscript.encoder(...),因爲直到函數不調用變量不eists後只能訪問變量。但不建議使用全局,你應該避免使用全局。

我想你想獲得該值不能訪問變量,以便更好地利用return語句 高清編碼器(INPUT_FILE): #一堆其他的代碼 #更多的代碼

# path to output of above code 
    return conv_output_file 
    conv_output_file = os.path.join(input_file_gs, output_format) 
    return conv_output_file 

或者乾脆

 return os.path.join(input_file_gs, output_format) 
相關問題