PHP에서 Python 파일 실행하고 결과 받아오기

1 개요[ | ]

PHP에서 Python 파일 실행하고 결과 받아오기

2 기본 실행[ | ]

root@localhost# cat hello.py
for i in range(3):
    print(i, 'I'm Python.')
root@localhost# python hello.py
0 I'm Python.
1 I'm Python.
2 I'm Python.
root@localhost# cat executor.php 
<?php
exec('python hello.py', $arr);
$result = implode("\n", $arr)."\n";
echo $result;
root@localhost# php executor.php 
0 I'm Python.
1 I'm Python.
2 I'm Python.

3 argument로 값 전달[ | ]

root@localhost# cat hello.py
import sys
for arg in sys.argv:
    print('arg:', arg)
root@localhost# python hello.py
arg: hello.py
root@localhost# python hello.py alice bob
arg: hello.py
arg: alice
arg: bob
root@localhost# cat executor.php
<?php
exec('python hello.py from php', $arr);
$result = implode("\n", $arr)."\n";
echo $result;
root@localhost# php executor.php
arg: hello.py
arg: from
arg: php

4 환경변수로 값 전달[ | ]

root@localhost# cat hello.py
import os
print('foo:', os.getenv('foo'))
print('monkey:', os.getenv('monkey'))
root@localhost# python hello.py
foo: None
monkey: None
root@localhost# foo=bar monkey=banana python hello.py
foo: bar
monkey: banana
root@localhost# cat executor.php
<?php
exec('foo=from monkey=php python hello.py', $arr);
$result = implode("\n", $arr)."\n";
echo $result;
root@localhost# php executor.php 
foo: from
monkey: php

5 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}