如何将文件作为stdin传递给php artisan自定义命令?
报错原因
执行
php artisan my_custom_command < file触发the input device is not a TTY报错,本质是自定义Artisan命令内部使用了ask()、secret()等需要TTY终端交互的方法,从文件重定向标准输入时无TTY环境,触发校验失败。
可行解决方案
- 方案1:添加
--no-interaction参数跳过交互校验
直接在命令后加-n(--no-interaction的缩写)即可关闭Artisan的交互检测,不需要修改命令代码:php artisan my_custom_command -n < file - 方案2:用管道或here string传递文件内容
用cat管道或者here string语法传递输入,适配部分特殊环境的重定向规则:# 管道写法 cat file | php artisan my_custom_command -n # here string写法 php artisan my_custom_command -n <<< "$(cat file)" - 方案3:用script命令模拟TTY环境
Linux/macOS下可以用系统自带的script工具模拟TTY终端,不需要修改命令,适合需要保留交互逻辑的场景:script -q /dev/null php artisan my_custom_command < file - 方案4:修改自定义命令支持直接传文件路径
最稳妥的方案是调整自定义命令的代码,新增文件路径参数/选项,直接读取指定文件内容,完全避开标准输入的TTY限制:- 在命令的
$signature属性中新增选项:
protected $signature = 'my_custom_command {--input= : 输入文件路径}';- 在handle方法中直接读取文件内容:
调用方式改为:public function handle() { $content = file_get_contents($this->option('input')); // 后续业务逻辑 }php artisan my_custom_command --input=./目标文件路径 - 在命令的
内容的提问来源于stack exchange,提问作者good_evening
相关产品推荐
相关产品推荐

