PHP exec():运行bash脚本来配置环境然后执行Python程序

时间:2021-01-07 00:08:53

Shell is tcsh. PHP v5.1.6. Redhat 5.7. Safe_mode is OFF.

壳牌是tcsh。 PHP v5.1.6。 Redhat 5.7。 Safe_mode已关闭。

Running php script from the browser using exec to:

使用exec从浏览器运行php脚本:

  1. configure environment via source command on bash script
  2. 在bash脚本上通过source命令配置环境
  3. run a python program relying on the environment set up by the bash script (program outputs to STDOUT)
  4. 运行一个依赖于bash脚本设置的环境的python程序(程序输出到STDOUT)

This works from the command line ($shell = tcsh):

这适用于命令行($ shell = tcsh):

/bin/bash -c "source /path-to-config-bash-script/config.sh; /bin/path-to-python /path-to-python-program/prog.py 2>&1"

This does not. Python program returns an error indicating that the environment is not set up correctly (can't find certain libraries, etc.):

这没有。 Python程序返回一个错误,指示环境设置不正确(无法找到某些库等):

<?php
....
$cmd = "/bin/bash -c \"source /path-to-config-bash-script/config.sh; /bin/path-to-python /path-to-python-program/prog.py 2>&1\"";
$ret_val = exec( $cmd, $ret_arr, $err );
?>

Quadruple-checked permissions and everything looks OK.

四重检查权限,一切看起来都不错。

Thanks!

谢谢!

1 个解决方案

#1


1  

Four things to note.

有四点需要注意。

1 - PHP must not have safe_mode on to leverage exec()

1 - PHP必须没有safe_mode才能利用exec()

2 - The shell script script needs to have #!/bin/bashto be declared at the top of the file rather than being passed into the exec()

2 - shell脚本脚本需要在文件顶部声明#!/ bin / bashto而不是传递给exec()

3 - The python script must have #!/usr/bin/python at the top of the script rather than attempting to execute it through the exec() statement.

3 - python脚本必须在脚本顶部有#!/ usr / bin / python,而不是试图通过exec()语句执行它。

4 - All directories that are traversed to get to the script must be readable.

4 - 遍历到脚本的所有目录都必须是可读的。

So the final should look like:

所以决赛应该是这样的:

$cmd = "/path-to-config-bash-script/config.sh; /path/to-python/program/prog.py 2>&1";

This should resolve all your issues.

这应该可以解决您的所有问题。

#1


1  

Four things to note.

有四点需要注意。

1 - PHP must not have safe_mode on to leverage exec()

1 - PHP必须没有safe_mode才能利用exec()

2 - The shell script script needs to have #!/bin/bashto be declared at the top of the file rather than being passed into the exec()

2 - shell脚本脚本需要在文件顶部声明#!/ bin / bashto而不是传递给exec()

3 - The python script must have #!/usr/bin/python at the top of the script rather than attempting to execute it through the exec() statement.

3 - python脚本必须在脚本顶部有#!/ usr / bin / python,而不是试图通过exec()语句执行它。

4 - All directories that are traversed to get to the script must be readable.

4 - 遍历到脚本的所有目录都必须是可读的。

So the final should look like:

所以决赛应该是这样的:

$cmd = "/path-to-config-bash-script/config.sh; /path/to-python/program/prog.py 2>&1";

This should resolve all your issues.

这应该可以解决您的所有问题。