<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Серый форум &mdash; CMD/BAT: Перенаправление вывода в GUI]]></title>
		<link>https://forum.script-coding.com/viewtopic.php?id=12113</link>
		<atom:link href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=12113&amp;type=rss" rel="self" type="application/rss+xml" />
		<description><![CDATA[Недавние сообщения в теме «CMD/BAT: Перенаправление вывода в GUI».]]></description>
		<lastBuildDate>Sat, 29 Oct 2016 22:48:16 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[CMD/BAT: Перенаправление вывода в GUI]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=108691#p108691</link>
			<description><![CDATA[<p>Скрипт для показа вывода консольной команды в GUI приложении. По сути, это многословная, гибкая и конфигурируемая обертка вокруг пары команд:<br /></p><div class="codebox"><pre><code>
команда &gt; &quot;временный-файл&quot;
приложение &quot;временный-файл&quot;
</code></pre></div><p>У меня есть некоторое приложение, которое генерирует HTML из некоторых данных. Надо было его посмотреть в браузере. И я не хотел заботиться о создании/хранении/удалении временного файла. В результате я однажды написал что-то такое простенькое. Потом его улучшил. Через какое-то время еще раз улучшил, а потом переписал в то, что получилось. </p><p><strong>Применение</strong></p><p>Показать в Блокноте<br /></p><div class="codebox"><pre><code>
команда | 2
</code></pre></div><p>Показать в браузере (например, Internet Explorer)<br /></p><div class="codebox"><pre><code>
команда | 2 html
</code></pre></div><p>Насторить показ в другом приложении (например, Firefox) с помощью вспомогательного файла 2.html.bat<br /></p><div class="codebox"><pre><code>
set &quot;pipecmd=%ProgramFiles%\Firefox\firefox.exe&quot;
</code></pre></div><p>Изменить способ отображения &quot;на лету&quot; (например, HTML показать как текст)<br /></p><div class="codebox"><pre><code>
команда | 2 html.txt
</code></pre></div><p><strong>Специальные возможности</strong><br /></p><div class="codebox"><pre><code>
-d DIR     использовать каталог DIR для временных файлов
-n NAME    использовать NAME как имя временного файла
--debug    включить отладку (показ переменных окружения)
--dry-run  &quot;сухой&quot; запуск, показать команды, как если бы они выполнились
</code></pre></div><p><strong>Переменные окружения</strong></p><p>%pipecmd%</p><p>(обязательный)<br />строка запуска приложения (может содержать дополнительные аргументы</p><p>%pipeext%</p><p>(опционально, но рекомендуется установить)<br />расширение (строка вида &quot;.txt&quot;, &quot;.html&quot; и т.д.) необходима для распознавания формата вывода. </p><p>%pipetmpsave%</p><p>(необязательный)<br />команда, используемая для сохранения потока во временнный файл. По умолчанию это команда &quot;more&quot;. </p><p><strong>Исходный код</strong></p><p><a href="https://github.com/ildar-shaimordanov/cmd.scripts/blob/master/bin/2.bat">https://github.com/ildar-shaimordanov/c … /bin/2.bat</a><br /><a href="https://github.com/ildar-shaimordanov/cmd.scripts/blob/master/bin/2.html.bat">https://github.com/ildar-shaimordanov/c … 2.html.bat</a></p><div class="codebox"><pre><code>
::HELP Redirects output of command line tools to GUI application.
::HELP
::HELP
::HELP USAGE
::HELP
::HELP command | 2 [OPTIONS] [APP[.EXT] | EXT] [APP-OPTIONS]
::HELP
::HELP
::HELP OPTIONS
::HELP
::HELP -d DIR     use DIR for storing temp files
::HELP -n NAME    use NAME as the name of temp file
::HELP --debug    turn on debug information
::HELP --dry-run  don&#039;t invoke a command, display only
::HELP
::HELP
::HELP DESCRIPTION
::HELP
::HELP The script is flexible enough to enable many ways to invoke GUI 
::HELP applications. Which GUI application would be invoked is defined by 
::HELP the arguments. Depending on what is this, it will be called to 
::HELP declare few specific environment variables. 
::HELP
::HELP
::HELP INVOCATION
::HELP
::HELP commands | 2
::HELP
::HELP With no parameters runs Notepad. Always. 
::HELP
::HELP commands | 2 APP
::HELP
::HELP &quot;APP&quot; is the parameter defining an application or a family of 
::HELP applications or an extension (without the leading &quot;dot&quot; symbol). 
::HELP The script looks around for the file called as &quot;2.APP.bat&quot;. If the 
::HELP file exists, invokes it to set the needful environment variables. 
::HELP The script should declare few specific environment variables (see 
::HELP the &quot;ENVIRONMENT&quot; section below). 
::HELP
::HELP commands | 2 APP.EXT
::HELP
::HELP The same as above but &quot;.EXT&quot; overrides early declared extension. 
::HELP
::HELP commands | 2 EXT
::HELP
::HELP If there is no file &quot;2.APP.bat&quot;, the argument is assumed as the 
::HELP extension (without the leading &quot;dor&quot; symbol), the script does 
::HELP attempt to find an executable command (using &quot;assoc&quot; and &quot;ftype&quot;) 
::HELP and prepare invocation of the command found by these commands. 
::HELP
::HELP
::HELP ENVIRONMENT
::HELP
::HELP %pipecmd%
::HELP
::HELP (Mandatory)
::HELP Invocation string for the application. It could or could not 
::HELP contain additional parameters supported by the application. 
::HELP
::HELP %pipeext%
::HELP
::HELP (Optional, but recommended to set)
::HELP Extenstion (like &quot;.txt&quot; or &quot;.html&quot; etc). It can be useful in the 
::HELP case if the application is able to handle different data files. 
::HELP
::HELP %pipetmpsave%
::HELP
::HELP (Optional)
::HELP The command line tool used for capturing output of commands and 
::HELP redirecting to a resulting file. By default it is set as follows: 
::HELP
::HELP set &quot;pipetmpsave=more&quot;
::HELP
::HELP Another possible setting is:
::HELP
::HELP set &quot;pipetmpsave=findstr &quot;$&quot;&quot;
::HELP
::HELP
::HELP CONFIGURATION
::HELP
::HELP Using the file &quot;2-settings.bat&quot; located in the same directory 
::HELP allows to configure the global environment variables of the main 
::HELP script. It is good place for setting such kind of variables as 
::HELP %pipetmpdir%, %pipetmpname% and %pipetmpsave%. 
::HELP
::HELP
::HELP SEE ALSO
::HELP
::HELP ASSOC /?
::HELP FTYPE /?

:: ========================================================================

@echo off

timeout /t 0 &gt;nul 2&gt;&amp;1 &amp;&amp; (
	call :pipe-help
	goto :EOF
)

:: ========================================================================

setlocal

set &quot;pipedbg=&quot;
set &quot;pipedry=&quot;

set &quot;pipetmpdir=%TEMP%&quot;
set &quot;pipetmpname=pipe.%RANDOM%&quot;
set &quot;pipetmpfile=&quot;
set &quot;pipetmpsave=more&quot;

if exist &quot;%~dpn0-settings.bat&quot; call &quot;%~dpn0-settings.bat&quot;

set &quot;pipecmd=&quot;
set &quot;pipecmdopts=&quot;
set &quot;pipetitle=&quot;
set &quot;pipeext=&quot;

:: ========================================================================

:pipe-options-begin

if &quot;%~1&quot; == &quot;&quot; goto :pipe-options-end

if &quot;%~1&quot; == &quot;-d&quot; (
	set &quot;pipetmpdir=%~2&quot;
	shift /1
	shift /1
) else if &quot;%~1&quot; == &quot;-n&quot; (
	set &quot;pipetmpname=%~2&quot;
	shift /1
	shift /1
) else if &quot;%~1&quot; == &quot;--debug&quot; (
	set &quot;pipedbg=1&quot;
	shift /1
) else if &quot;%~1&quot; == &quot;--dry-run&quot; (
	set &quot;pipedry=1&quot;
	shift /1
) else (
	goto :pipe-options-end
)

goto :pipe-options-begin
:pipe-options-end

:: ========================================================================

if &quot;%~1&quot; == &quot;&quot; (

	rem command | 2

	set &quot;pipecmd=notepad&quot;
	set &quot;pipetitle=[app = notepad]&quot;
	set &quot;pipeext=.txt&quot;

) else if exist &quot;%~dpn0.%~n1.bat&quot; (

	rem command | 2 app[.ext]

	call :pipe-configure &quot;%~dpn0.%~n1.bat&quot; &quot;%~x1&quot;

	set &quot;pipetitle=[app = %~n1]&quot;
	if not defined pipeext set &quot;pipeext=%~n1&quot;
	if not &quot;%~x1&quot; == &quot;&quot; set &quot;pipeext=%~x1&quot;

	shift /1

) else (

	rem command | 2 ext

	for /f &quot;tokens=1,* delims==&quot; %%a in ( &#039;
		2^&gt;nul assoc &quot;.%~n1&quot;
	&#039; ) do for /f &quot;tokens=1,* delims==&quot; %%c in ( &#039;
		2^&gt;nul ftype &quot;%%b&quot;
	&#039; ) do (

		set &quot;pipecmd=%%d&quot;
		set &quot;pipetitle=[%%a = %%b]&quot;
		set &quot;pipeext=%%a&quot;

	)
	if not &quot;%~x1&quot; == &quot;&quot; set &quot;pipeext=%~x1&quot;

	shift /1

)

if defined pipedbg call :pipe-debug &quot;After parsing options&quot;

:: ========================================================================

if not defined pipecmd (
	&gt;&amp;2 echo:Bad invocation
	goto :EOF
)

:: ========================================================================

if not defined pipeext set &quot;pipeext=.txt&quot;
if not defined pipetitle set &quot;pipetitle=[%pipeext%]&quot;

for %%f in ( &quot;%pipetmpdir%&quot; ) do set &quot;pipetmpfile=%%~ff\%pipetmpname%%pipeext%&quot;

:: ========================================================================

setlocal enabledelayedexpansion

set &quot;pipecmdopt=&quot;

:pipe-app-options-begin
set pipecmdopt=%1
if not defined pipecmdopt goto :pipe-app-options-end

set &quot;pipecmdopts=%pipecmdopts% %pipecmdopt%&quot;
shift /1

goto :pipe-app-options-begin
:pipe-app-options-end

set &quot;pipecmd=!pipecmd:%%1=&quot;%%1&quot;!&quot;
set &quot;pipecmd=!pipecmd:&quot;&quot;%%1&quot;&quot;=&quot;%%1&quot;!&quot;
if &quot;!pipecmd!&quot; == &quot;!pipecmd:%%1=!&quot; set &quot;pipecmd=!pipecmd! &quot;%%1&quot;&quot;
set &quot;pipecmd=!pipecmd:%%1=%pipetmpfile%!&quot;

endlocal &amp; set &quot;pipecmd=%pipecmd%&quot; &amp; set &quot;pipecmdopts=%pipecmdopts%&quot;

:: ========================================================================

if defined pipedbg call :pipe-debug &quot;Before invocation&quot;

call :pipe-invoke %pipecmdopts%

endlocal
goto :EOF

:: ========================================================================

:pipe-configure
setlocal
call &quot;%~1&quot; &quot;%~2&quot;
endlocal &amp; set &quot;pipecmd=%pipecmd%&quot; &amp; set &quot;pipeext=%pipeext%&quot; &amp; set &quot;pipetmpsave=%pipetmpsave%&quot;
goto :EOF

:pipe-invoke
if defined pipedry (
	echo:Invocation ^(dry-run^)
	echo:call %pipetmpsave% ^&gt; &quot;%pipetmpfile%&quot;
	echo:call start &quot;Starting %pipetitle%&quot; %pipecmd%
	goto :EOF
)

call %pipetmpsave% &gt; &quot;%pipetmpfile%&quot;
call start &quot;Starting %pipetitle%&quot; %pipecmd%
goto :EOF

:: ========================================================================

:pipe-help
for /f &quot;tokens=1,* delims= &quot; %%a in ( &#039;
	findstr /b &quot;::HELP&quot; &quot;%~f0&quot;
&#039; ) do (
	echo:%%~b
)
goto :EOF

:pipe-debug
echo:%~1...
set pipe
echo:
goto :EOF

:: ========================================================================

:: EOF
</code></pre></div>]]></description>
			<author><![CDATA[null@example.com (Rumata)]]></author>
			<pubDate>Sat, 29 Oct 2016 22:48:16 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=108691#p108691</guid>
		</item>
	</channel>
</rss>
