How to pause the execution of a command line script to give the user the possibility to exit it with a Ctrl+C?
For example I have this script for deleting a user id from a number of tables, but would like to halt the scrip开发者_Python百科t before really doing it:
<?php
define('DBHOST', '/tmp');
define('DBNAME', 'XXX');
define('DBUSER', 'YYY');
define('DBPASS', 'ZZZ');
$TABLES = array('pref_game',
'pref_hand',
'pref_luck',
'pref_match',
'pref_misere',
'pref_money',
'pref_pass',
'pref_rep',
'pref_status',
'pref_users'
);
if ($argc != 2)
exit("Missing user id\n");
if (!preg_match('/^([A-Z]{2}[0-9]+)$/', $argv[1], $matches))
exit("Invalid user id\n");
$id = $matches[1];
printf("Deleting user %s Press CTRL-C to abort\n\n", $id);
# XXX stop here, but how? XXX
try {
$db = new PDO('pgsql:host=' . DBHOST . '; dbname=' . DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach ($TABLES as $table) {
$sql = sprintf('delete from %s where id=?', $table);
run_sql($db, $sql, $id);
}
} catch (Exception $e) {
exit('Database problem: ' . $e->getMessage());
}
function run_sql($db, $sql, $arg) {
$sth = $db->prepare($sql);
$sth->execute(array($arg));
printf("SQL: %s\nAffected rows: %d\n\n", $sql, $sth->rowCount());
}
?>
Using CentOS Linux 5.5 + PHP 5.1.6 + PostgreSQL 8.4.7.
Try with:
printf("Deleting user %s Press CTRL-C to abort, enter to continue\n\n", $id);
$fp = fopen("php://stdin","r");
fgets($fp);
echo "OK!";
sleep(5);
would wait for five seconds.
If you want something more fancy:
function delay($duration) {
while($duration) {
echo "\rStarting in ".$duration--.'...';
sleep(1);
}
echo "\n";
}
If you don't want to sleep but prefer a yes/no-style prompt:
function confirm($question) {
while(true) {
$line = strtolower(trim(readline($question.'? [Y/n]')));
if(!$line || $line == 'y') {
return true;
}
elseif($line == 'n') {
return false;
}
}
}
Use sleep()
or read from stdin until you get a newline: http://php.net/manual/en/wrappers.php.php
精彩评论