0

Like the file says I am executing a python script from a PHP file sitting on my apache webserver. The example I have is extremely basic.

PHP file -- test.php

<?php
echo "hello";
echo exec("/usr/local/bin/python2.7 test1.py");
?>

python script -- test1.py

print "world"
fh = open ('testtest' ,'r')
for line in fh:
    print line

contents of -- testtest

abcdefg

'world' prints when I don't have the bottom 2 lines of test1.py but it stops printing as soon as I add for line in file: Thank you. Edit: I'm trying to print the contents of testtest.

9
  • There's an error in your code on the third line of test.php, you forgot to close parenthesis. Commented Aug 3, 2011 at 21:10
  • What happens if you run the python script directly? Commented Aug 3, 2011 at 21:12
  • Can you check your apache logs? Python could be raising an AttributeError if open returns None. Also, 'r' is implied by open, so you can just do for line in open('testtest'):, or even better, make use of the with keyword. Commented Aug 3, 2011 at 21:13
  • @brainstorm the syntax error was my fault. That parenthesis isn't missing in my php file (I just checked). Commented Aug 3, 2011 at 21:16
  • @Jack M. the output of this when I open the php page in a browser is hello Commented Aug 3, 2011 at 21:17

2 Answers 2

3

exec does not do what you expect it to do. The documentation states that it only returns the last line of output. It recommends use of passthru instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I'll give you the green check once I try it out but this makes a lot of sense now....
passthru worked. It should be noted, if you want to read from a file you must have +x on that file. I had to chmod 777 testtest as well
0

You don't want to assign to the variable file. That's a built-in in Python. You should use something like fh for file handle, or inFile, or the like. That might be enough to address it.

3 Comments

@Rell3oT - Sure thing. And you said you'd tried absolute paths to the file in question? If you import sys and print sys.path what does it come up with? Does it contain the directory where your script resides? If not, sys.path.append() would let you specify it.
Python built-ins are just references, assigning to them never does anything bad, especially because it only affects the local scope, never modules. It's not necessarily good practice, but never really bad.
Wow, i definitely wasn't expecting sys.path to be a list. Yeah, sys.path contains the directory where testtest test.php and test1.py reside.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.