PHP에서 Python 스크립트 실행
다음 명령을 사용하여 PHP에서 Python 스크립트를 실행하려고합니다.
exec('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
그러나 PHP는 단순히 출력을 생성하지 않습니다. 오류보고는 E_ALL로 설정되고 display_errors는 켜져 있습니다.
내가 시도한 것은 다음과 같습니다.
- 내가 사용
python2
,/usr/bin/python2
그리고python2.7
대신/usr/bin/python2.7
- 나는 또한 아무것도 변경하지 않은 절대 경로 대신 상대 경로를 사용했습니다.
- 내가 명령을 사용하여 시도
exec
,shell_exec
,system
.
그러나 내가 달리면
if (exec('echo TEST') == 'TEST')
{
echo 'exec works!';
}
shutdown now
아무것도하지 않는 동안 완벽하게 잘 작동합니다 .
PHP에는 파일에 액세스하고 실행할 수있는 권한이 있습니다.
편집 : Alejandro 덕분에 문제를 해결할 수있었습니다. 동일한 문제가 발생하면 웹 서버가 아마도 루트로 실행되지 않을 것임을 잊지 마십시오. 웹 서버의 사용자 또는 유사한 권한을 가진 사용자로 로그인하고 직접 명령을 실행 해보십시오.
Ubuntu Server 10.04에서 테스트되었습니다. Arch Linux에서도 도움이되기를 바랍니다.
PHP 에서는 shell_exec 함수를 사용합니다 .
쉘을 통해 명령을 실행하고 전체 출력을 문자열로 반환합니다.
실행 된 명령의 출력을 반환하거나 오류가 발생했거나 명령이 출력을 생성하지 않으면 NULL을 반환합니다.
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
Python 파일 test.py
에서 첫 번째 줄에있는이 텍스트를 확인합니다. (shebang 설명 참조) :
#!/usr/bin/env python
또한 Python 파일 에는 올바른 권한 (PHP 스크립트가 브라우저 또는 컬에서 실행되는 경우 사용자 www-data / apache에 대한 실행)이 있어야하고 /하거나 "실행 가능"해야합니다. 또한 .py
파일에 대한 모든 명령 에는 올바른 권한이 있어야합니다.
촬영 PHP 매뉴얼에서 :
유닉스 유형 플랫폼에서 shell_exec를 사용하려고하는데 작동하지 않는 것 같은 사람들을위한 간단한 알림입니다. PHP는 시스템에서 웹 사용자로 실행되므로 (일반적으로 Apache의 경우 www) 웹 사용자가 shell_exec 명령에서 사용하려는 파일이나 디렉토리에 대한 권한을 가지고 있는지 확인해야합니다. 그렇지 않으면 아무것도하지 않는 것처럼 보입니다.
유닉스 유형 플랫폼에서 실행 파일 을 만들 려면 다음을 수행하십시오.
chmod +x myscript.py
passthru
출력 버퍼를 직접 사용 하고 처리하는 것이 좋습니다 .
ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean();
명령의 반환 상태를 알고 전체 stdout
출력을 얻으려면 실제로 사용할 수 있습니다 exec
.
$command = 'ls';
exec($command, $out, $status);
$out
모든 행의 배열입니다. $status
반환 상태입니다. 디버깅에 매우 유용합니다.
당신은 또한보고 싶다면 stderr
출력을 당신도 함께 플레이 할 수 proc_open 하거나 추가 할 2>&1
당신에게 $command
. 후자는 종종 작업을 수행하고 "구현"하는 데 더 빨리 충분합니다.
Alejandro는 예외에 대한 설명을 추가했습니다 (Ubuntu 또는 Debian)-답변 자체에 추가 할 담당자가 없습니다.
sudoers 파일 : sudo visudo
예외 추가 : www-data ALL=(ALL) NOPASSWD: ALL
상황에 따라 사용할 명령을 명확히하려면
exec()
-외부 프로그램 실행
system()
- Execute an external program and display the output
passthru()
- Execute an external program and display raw output
Source: http://php.net/manual/en/function.exec.php
In my case I needed to create a new folder in the www
directory called scripts
. Within scripts
I added a new file called test.py
.
I then used sudo chown www-data:root scripts
and sudo chown www-data:root test.py
.
Then I went to the new scripts
directory and used sudo chmod +x test.py
.
My test.py file it looks like this. Note the different Python version:
#!/usr/bin/env python3.5
print("Hello World!")
From php I now do this:
$message = exec("/var/www/scripts/test.py 2>&1");
print_r($message);
And you should see: Hello World!
The above methods seem to be complex. Use my method as a reference.
I have these two files:
run.php
mkdir.py
Here, I've created an HTML page which contains a GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.
run.php
<html>
<body>
<head>
<title>
run
</title>
</head>
<form method="post">
<input type="submit" value="GO" name="GO">
</form>
</body>
</html>
<?php
if(isset($_POST['GO']))
{
shell_exec("python /var/www/html/lab/mkdir.py");
echo"success";
}
?>
mkdir.py
#!/usr/bin/env python
import os
os.makedirs("thisfolder");
This is so trivial, but just wanted to help anyone who already followed along Alejandro's suggestion but encountered this error:
sh: blabla.py: command not found
If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:
$command = escapeshellcmd('python blabla.py');
참고URL : https://stackoverflow.com/questions/19735250/running-a-python-script-from-php
'program tip' 카테고리의 다른 글
JFrame 아이콘 변경 방법 (0) | 2020.08.19 |
---|---|
XML 파일을 XmlDocument로 읽기 (0) | 2020.08.19 |
JQuery에는 왜 모든 곳에 달러 기호가 있습니까? (0) | 2020.08.19 |
Google Play에서 Android 앱의 패키지 이름을 변경할 수 있나요? (0) | 2020.08.19 |
Web Api 용 Xml 문서에 기본 프로젝트 이외의 문서를 포함하려면 어떻게해야합니까? (0) | 2020.08.19 |