我在命令行上运行了一个 php (v. 7.0.16) 脚本:
$ct = 1;
foreach($sort_this as $cur_site_id => $dx){
$cur_location = $locations[$cur_site_id]['location'];
$msg = "\033[A\33[2K\r" . 'getting data for %25s (' . $cur_site_id . ') store: %7s %01.2f' . "\n";
echo printf($msg, $cur_location, ($ct . ' / ' . count($sort_this)), number_format((($ct / count($sort_this)) * 100), 2));
$ct++;
}
这个循环运行大约 40 次迭代。 printf 语句适用于 1 个小问题。在“获取数据”行之后的行上,我看到一个数字在运行时从 7x-7y 递增(有时从 71 开始,有时从 77 开始,等等)。我不知道是什么导致了这个数字被打印出来。因此,当循环开始时,我会在屏幕上看到类似这样的内容:
getting data for DENVER (531) store: 42 / 42 0.00
77
当它完成这样的事情时:
getting data for SEATTLE (784) store: 42 / 42 100.00
79
我在这里找到了如何打印到同一行并清除数据:
Erase the current printed console line
有没有办法阻止 7x 代码显示?还有,它们是什么?
最佳答案
问题出在这一行:
echo printf(...)
printf()
使用其参数(格式和值)生成一个字符串并打印它。它返回打印字符的数量(它生成的字符串的长度)。
然后您的代码将此值传递给 echo
打印它。这是 70-77 范围内的额外数字的来源。
您应该删除 echo
或使用 sprintf()
而不是 printf()
.
sprintf()
生成与 printf()
相同的字符串,但它不打印它;它返回它并作为参数传递给显示它的 echo
。
关于php - CLI php中的printf在行尾打印额外的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43526399/