簡體   English   中英

Python:從網絡界面運行時導入其他python文件

[英]Python: Import other python files while running from web interface

我正在Apache服務器中運行從php調用的python腳本。 如果我想從相同/不同的文件夾導入python文件,該怎么做? 我的apache服務器在一個目錄中運行,但是python代碼在另一個目錄中。 那么如何關聯這兩個目錄結構?

我通常在變量中使用要導入的文件中的值(例如file2.py)。

+ apacheFolder
| folder1
| +folder2
  |- index.html
  |+ pythonFileDir
     |-__init__.py
     |-file1.py
     |-file2.py
     |-file3.py

我嘗試在file1.py執行以下導入命令,

import file2

但這對我沒有幫助。 我正在從php文件中調用file1.py,

shell_exec("[pythonInstallDir]/python.exe [pythonFileDir]/file1.py arg1 arg2");

依次由html表單操作觸發器調用此php。

嘗試pythonFileDir __init__.py放入pythonFileDir然后重試。 根據您最初從何處調用file1.py ,這可能會更改file2.py的調用方式。 您可能需要使用from pythonFileDir import file2來調用file2.py

之所以調用file1.py但找不到file2.py的原因是由於file1.py的調用方式。

shell_exec("[pythonInstallDir]/python.exe [pythonFileDir]/file1.py arg1 arg2");

file1.py將嘗試從與執行shell_exec相同的目錄中查找file2.py (很可能是從中調用它的PHP路徑或Web目錄),因此在完全不同的目錄中搜索file2.py (遠遠離pythonFileDir )。

您可以嘗試使用以下命令通過shell_exec來更改目錄:

shell_exec("cd [pythonFileDir]; [pythonInstallDir]/python.exe file1.py arg1 arg2");

這樣,您實際上將在pythonFileDir內部執行,並且找到file2.py不會有任何問題。

因此,一個完整的例子是:

shell_exec(“ cd c:\\ path \\ to \\ pythonFileDir; [pythonInstallDir] /python.exe file1.py arg1 arg2”);

或者您可以嘗試強制PHP更改目錄,而不是在shell_exec()命令中完成所有操作:

chdir( 'C:\path\to\pythonFileDir' );
shell_exec("[pythonInstallDir]/python.exe file1.py arg1 arg2");

正如@sth所問,Max Worg已經提到過。 我不確定如何從php調用file1.py,但是可以嘗試將python目錄添加到python路徑中?

在file1.py中

import sys
# either absolute or relative path to pythonFolderDir in file1.py
sys.path.append('/home/user/apacheFolder/folder2/pythonFolderDir');
import file2.py

我認為這不是一個好主意,但這將是關聯目錄的一種方法。

您可以通過在Python中實現套接字來構建Web服務器。 您有一個類,該類產生一個作為偵聽器的線程,以及一個包含其他python對象的線程。 從那里,當對象線程檢測到您可以在類中指定的文件中的更改時,可以重新導入對象線程。 您只需要在其中放置一個使用os.listdir的while循環,就可以對文件進行哈希處理,或者只是看看它們是否只是增加了,這取決於您。 現在,您可以通過網絡進行通信,並且可以為您重新加載模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM