Найти - Пользователи
Полная версия: Эквивалент bash'овского read
Начало » Python для новичков » Эквивалент bash'овского read
1
Virtul
День добрый, подскажите, пожалуйста, как добиться сто процентной копии работы такого простенького башовского скрипта:
#!/bin/sh
while read line; do
    echo "ERR!$line"
done

В системке racktables есть поддержка неких gateways - php код банально вызывает внешние скрипты передавая в них команды на stdin и читает stdout
собственно код выше - работает, этот тоже:
#!/bin/env perl
while (<>) {
    print;
}

Но запустить пайтон скрипты никак не выходит - пробовал raw_input(), os.stdin, fileinput.input() но ни в какую, поможите кто чем может пожалуйста :) Заранее благодарю
s0rg
import sys
data = sys.stdin.read()
в data - будет то, что пришло на вход
Rodegast
while not raw_input() == False:
	print "ERR!$line"
или
while True:
	raw_input()
	print "ERR!$line"
doza_and
2.x:
import sys
for x in sys.stdin:
    print x,
3.x
import sys
for x in sys.stdin:
    print(x, end="")
Virtul
Всем спасибо, но ни один предложенный вариант не сработал, я понятия не имею в чём разница (с консоли всё выглядит одинаково), но работал только вот такой вариант:
#!/bin/env python2.6
import sys
line = sys.stdin.readline()
while line:
    print line,
    line = sys.stdin.readline()

Найдётся ли знаток, который объяснит разницу? :)

Вот вызывающая функция php:
function queryGateway ($gwname, $questions)
{
	global $racktables_gwdir;
	$execpath = "${racktables_gwdir}/{$gwname}/main";
	$dspec = array
	(
		0 => array ("pipe", "r"),
		1 => array ("pipe", "w"),
		2 => array ("file", "/dev/null", "a")
	);
	$pipes = array();
	$gateway = proc_open ($execpath, $dspec, $pipes);
	if (!is_resource ($gateway))
		return array ('ERR proc_open() failed in ' . __FUNCTION__);
	foreach ($questions as $q)
		fwrite ($pipes[0], "$q\n");
	fclose ($pipes[0]);
	$answers = array ();
	while (!feof($pipes[1]))
	{
		$a = fgets ($pipes[1]);
		if (!strlen ($a))
			continue;
		// Somehow I got a space appended at the end. Kick it.
		$answers[] = trim ($a);
	}
	fclose($pipes[1]);
	$retval = proc_close ($gateway);
	if ($retval != 0)
		throw new RTGatewayError ("gateway failed with code ${retval}");
	if (!count ($answers))
		throw new RTGatewayError ('no response from gateway');
	if (count ($answers) != count ($questions))
		throw new RTGatewayError ('protocol violation');
	foreach ($answers as $a)
		if (strpos ($a, 'OK!') !== 0)
			throw new RTGatewayError ("subcommand failed with status: ${a}");
	return $answers;
}

а вот этот код вообще вешает страницу с вызовом queryGateway намертво:
#!/bin/env python2.6
import sys
while 1:
    x = sys.stdin.readline()
    print x,
s0rg
Virtul
ни один предложенный вариант не сработал, я понятия не имею в чём разница
Virtul
а вот этот код вообще вешает страницу с вызовом queryGateway намертво:
Есть мнение, что это все из-за буфферизации, вам нужно посмотреть в доках php (сам с ним, почти, не работаю) как ее отключить для ваших каналов.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB