简体   繁体   中英

“no such file or directory” in python script calling other python script in debian linux

Hi I've got the following written in a python script pythonscript1.py in linux debian in the directory /home/user/a/:

import subprocess
subprocess.call(["python" /home/user/b/phpcall.py"])

where the phpcall.py script contains:

import subprocess
subprocess.call(["php", "/home/user/b/phpscript1.php"])

individually called from console all scripts function perfectly, but when I use the first script whilst the 2nd script calls/looks for a file in directory b, rather than a, It yields the following error:

"PHP warning: include_once(something.php): failed to open stream: no such file in /home/user/b/phpschript1.php on line 25

Now it is quite clear to me the problem is that it cannot reach out of it's original directory. But I don't know what command I should add to the first script to allow the 2nd script to look in folder b.

So far google results have suggested something with "include_path='include'" but I don't know how/where to incorporate the statement succesfully.

Any suggestions on the correct syntax would be appreciated!

For future reference the code that directly called the php script from python within was:

import os
os.chdir("/home/user/b")
os.system("php /home/user/b/phpscript1.php")

.Thanks Marc B & I love the dynamic approach Sebastian, thank you :)

you can try this program:

import subprocess
import sys
proc = subprocess.Popen(
       [sys.executable, '/home/user/b/phpcall.py'],stdin=subprocess.PIPE)

proc.communicate()

i think it's work. if not let know.

If the php script works only if you start it from the directory with the python script then you could use cwd parameter to change the working directory for the subprocess:

#!/usr/bin/env python
from subprocess import check_call

check_call(["php", "/home/user/b/phpscript1.php"], cwd="/home/user/b")

I've added the shebang #!/usr/bin/env python so that you could run the script directly as /path/to/phpcall.py assuming it is executable ( chmod +x phpcall.py ).

Note: if you want to run the python script as user user then you could specify the path using ~ :

#!/usr/bin/env python
import os
from subprocess import check_call

script_dir = os.path.expanduser("~/b")
check_call(["php", os.path.join(script_dir, "phpscript1.php")], cwd=script_dir)

To avoid hardcoding the script directory, you could find it dynamically:

#!/usr/bin/env python
import os
from subprocess import check_call

script_dir = get_script_dir()
check_call(["php", os.path.join(script_dir, "phpscript1.php")], cwd=script_dir)

where get_script_dir() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM