I am running a nginx web server, along with PHP-CGI.
I would like to know if it is possible to execute a Python script inside PHP pages, allowing both languages to be combined. I've attempted it briefly but it didn't work, so I'm not sure how I would do this. Here are the two files I used:
index.php
<body>
<p>Hello! Here is a message: <?php exec('python hello.py'); ?></p>
</body>
hello.py
print 'Hello World!'
Any clues would be appreciated.
asked May 30, 2012 at 1:40
Markum
4,0899 gold badges28 silver badges30 bronze badges
-
I would do it exactly how you did it. What about it didn't work when you tried that? Could be an issue with the directory python gets executed in. Try an absolute path and see if it works thenMatt Dodge– Matt Dodge2012年05月30日 01:42:38 +00:00Commented May 30, 2012 at 1:42
-
The message didn't print on the page. And I tried changing both python and the filename to their absolute paths, still having the issue.Markum– Markum2012年05月30日 01:45:27 +00:00Commented May 30, 2012 at 1:45
-
ah I think you need an echo there, didn't see that at first. I posted it as an answer below for referenceMatt Dodge– Matt Dodge2012年05月30日 01:51:53 +00:00Commented May 30, 2012 at 1:51
1 Answer 1
exec will return the output of the shell command, but you still need to echo that to the page. The following code should work for you
<body>
<p>Hello! Here is a message: <?php echo exec('python hello.py'); ?></p>
</body>
answered May 30, 2012 at 1:51
Matt Dodge
11.3k7 gold badges42 silver badges58 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Markum
This partially works. I tried putting two print commands in my script and it only printed the second one in the page, any idea?
Matt Dodge
Check out the php docs on exec, the second parameter is a reference parameter called output where the output will be stored if there is multiple lines. This will slightly change the example in this answer obviously
default