php - 在 Laravel 中运行 python 脚本,脚本运行但未完全执行?

标签 php python laravel python-3.x shell

在我的机器上的本地 Apache 设置上运行,并且我在 Laravel 之外使用 python。

使用 Laravel 5.4,我已经制作并注册了该命令。我可以使用 php artisan python:printIt 来调用它很好。

我成功运行了该命令。 。 。但文件没有写入!这是控制台消息:

$ php artisan python:printIt In command handle for printIt. Running command. Command is : C:\Users\Cortland\Miniconda3\python.exe C:^\wamp64^\www^\cmrd^\cgi-bin^\py-test^\printer.pySuccess. Here is the return value: This message came from the python script.1

通过 python shell 或命令行运行时,python 脚本没有问题。这里,必须运行脚本,因为它具有正确的 print 消息。但是,exec 返回值是 1,即失败。

确认失败,因为不存在文件“pyfyle.txt”。

我做错了什么,如何解决? 真正的应用程序会涉及更多,但必须先确保我可以操作基本的脚本调用。

Laravel 命令类:

printIt.php

class printIt extends Command
{
    protected $signature = 'python:printIt';

    protected $description = 'Run the test python command.';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        echo "In command handle for printIt.\n";
        exec("where python", $path);

        $cmd = base_path('cgi-bin\py-test\printer.py');

        // "path/to/python command"
        $run = $path[0] . ' ' . escapeshellcmd($cmd);

        try {
            echo "Running command.\n";
            echo "Command is : " . $run;
            $res = exec($run, $out, $res);

            if ($res == 1) {
                throw \Exception("Could not run the sript");
            } else {
                echo "Success. Here is the return value: ", print_r($res);
            }
        } catch (\Exception $e) {
            echo "Error running command. It says " . $e->getMessage();
        }
    }
}

Python 脚本:

打印机.py

with open('pyfyle.txt', 'w', encoding='utf-8') as f:
    f.write('new text here.')
    f.close

// Edit: error, incorrect call to close: change f.close to f.close()

print("This message came from the python script..")

最佳答案

在控制台中输入:

sudo chmod +x printer.py

授予Python脚本执行权限。

这适用于 Linux 发行版,但如果看到输出中有“C:\”,则意味着您正在运行 Windows。

在这种情况下:

you need to add .py to the PATHEXT environment variable.

按照:https://docs.python.org/3/faq/windows.html#how-do-i-make-python-scripts-executable

关于php - 在 Laravel 中运行 python 脚本,脚本运行但未完全执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44866080/

相关文章:

php - 内爆时数组的 round() 内容达到特定的精度水平?

php - 仅显示数据库中用户名的字母

php - 在 root 的 android 平板电脑上本地 Web 服务器的缺点?

php - C++/CURL - 通过 PHP 请求安全方式传递数据?

python - 在 mongoengine 中更新嵌入式文档列表字段的正确方法是什么?

python - __getslice__ 在函数中怎么调用

laravel - php工匠路线上的ReflectionException错误

python - 如何在不从代码中删除日志语句的情况下关闭它们

mysql - Laravel 添加选择查询返回错误结果

laravel - 如何修复 "Predis\Response\ServerException ERR syntax error"?