2010-07-18 33 views
1

我可以簡單地使用PHP執行Python程序嗎? (在瀏覽器中)使用PHP執行Python程序

exec("python myProgram /Applications/MAMP/htdocs/somefile.xml"); 

或像這樣:

exec("/path/to/python path/to/myProgram /Applications/MAMP/htdocs/somefile.xml"); 

有任何這類方法正確嗎?

如果不是,應該採取什麼正確的方法來做到這一點?

謝謝

+1

任何特別的原因,爲什麼你不能使用PHP或者Python只?即:您可以將python程序翻譯成php – quantumSoup 2010-07-18 17:28:38

+0

我使用PHP生成XML字符串,然後需要將其作爲輸入傳遞給python腳本。就像我在終端窗口中所做的那樣:>>> myprogram myfile.xml ....基本上python腳本接受一個xml文件並處理它以生成一個字體文件。 – ssdesign 2010-07-18 17:37:15

+0

你使用的是什麼Python程序? – quantumSoup 2010-07-18 17:45:11

回答

1

通過MVDS的建議,你可以,我寧願使用proc_open()寫入STDIN,也不從STDOUT中讀取exec()/shell_exec(),以及提供您自己的一組環境變量 - $_ENV

一個示例代碼段從我的代碼中提取:

$process = proc_open(
    "{$command}", 
    array(   
    array('pipe', 'r'), 
    array('pipe', 'w'), 
    array('pipe', 'w') 
    ), 
    $pipes, 
    NULL, 
    $_ENV 
); 

if(is_resource($process)){ 

    fwrite($pipes[0], $string); 
    fclose($pipes[0]); 

    $rt = stream_get_contents($pipes[1]); 
    fclose($pipes[1]); 

    $rtErr = stream_get_contents($pipes[2]); 
    fclose($pipes[2]); 

    $exitCode = proc_close($process); 

} 

瞭解更多:http://php.net/manual/en/function.proc-open.php

0

是的,爲什麼不呢?

請注意,在頁面正在被預處理的同時,您並未在瀏覽器中執行此操作,而是在服務器端執行此操作。

考慮到該網頁在exec完成之前不會返回,因此它確實取決於您正在嘗試執行的操作。

+0

基本上我有一個python程序,我可以在終端(mac)上像這樣成功運行:>>> myptogram myfile.xml .....現在我試圖用PHP實現相同的功能。如果按照我在帖子中顯示的方式進行操作,結果是否與我的終端窗口方法相同? – ssdesign 2010-07-18 17:28:11

+1

檢查了這tooo .... intresting http://www.php.net/manual/en/language.operators.execution.php – 2010-07-18 17:35:24

+0

@ssdesign是的,但爲什麼你不能只是用PHP重寫你的Python程序?因爲依靠exec()意味着你需要在代碼運行的任何地方設置python,並確保你可以使用exec() – quantumSoup 2010-07-18 17:38:44

1

,如果你想捕捉輸出爲好,使用proc_open(全FD連接,即輸入和輸出)或popen(符合或輸出)