在我的机器上的本地 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/