0

I've got a problem with a python script. The script itself generates a string and writes it at the end to a file. This works well when I call the python script directly.

But as soon as I call the python script from PHP with exec(), it can't write to the file anymore.

In python I simply use:

try:
    FILE = open(filename,"w")
    FILE.write(mystring)
except IOError:
    print 'cannot open', filename

and PHP calls the python script like this:

$command = 'python myscript.py input1 input2 > /dev/null &';
exec($command, $stdout, $error);

Does anyone know what to do solve the problem?

6
  • 2
    Maybe the process running your PHP script has different permissions than your local user? Commented Dec 6, 2011 at 13:08
  • Are the permissions for the PHP process set properly? Commented Dec 6, 2011 at 13:08
  • Have you tried setting the permissions on your destination file so that it is open and world writeable? Commented Dec 6, 2011 at 13:08
  • do you close your file after writing?. Use with context manager Commented Dec 6, 2011 at 13:10
  • are you sure the command is running? consider the system or passthru functions that allow you to get return code or program output. Commented Dec 6, 2011 at 13:12

3 Answers 3

1

it can't write to the file

What error message are you getting? I notice that you are reporting an error in the Python script using a straight print to stdout, and redirecting stdout to /dev/null when running. The stderror string is a useful part of an IOError exception. You could change your except to something like this:

except IOError, err:
    sys.stderr.write("Could not open "+ err.filename + ": " + err.strerror + "\n")   

or you could use stdout and redirect the output to a real file instead of /dev/null - at least until you have nailed the problem.

0

Is filename a relative or absolute path? I would recommend using absolute paths so your script will work however it's called - for example "/home/matt/scripts/python/test.txt" is an absolute path.

This is a common error with scripts called by other scripts, or called by system events or cronjobs, etc.

Hope that helps

1
  • i tried it with relative and absolute path. both did not work. :( Commented Dec 6, 2011 at 14:06
0

There is a system-function which you can find in PHP manual: http://php.net/manual/en/function.system.php

$var = system('python sample.py myargs', $ref);

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.