Run / RunWait

외부 프로그램을 실행합니다. Run과 다르게, RunWait는 실행을 계속하기 전에 프로그램이 끝날 때까지 기다립니다.

Run, Target , WorkingDir, Options, OutputVarPID
RunWait, Target , WorkingDir, Options, OutputVarPID

매개변수

Target

기동할 문서, URL, 실행 파일 (.exe, .com, .bat, etc.), 단축 아이콘 (.lnk), 또는 문맥 메뉴 (논평 참조). Target이 지역 파일이고 경로가 지정되어 있지 않으면, A_WorkingDir이 제일 먼저 검색됩니다. 거기에서 부합하는 파일이 없으면, 운영체제는 ("알고 있는") PATH 폴더를 검색해 발견하면 그 파일을 기동합니다.

매개변수를 건네려면, 프로그램이나 문서 이름 다음에 바로 그것들을 추가합니다. For example, Run, MyProgram.exe Param1 Param2.

If the program/document name or a parameter contains spaces, it is safest to enclose it in double quotes (even though it may work without them in some cases). For example, Run, "My Program.exe" "param with spaces".

WorkingDir

기동된 항목을 위한 작업 디렉토리. 안에 스페이스가 있더라도 이름을 겹따옴표로 둘러싸지 마십시오. 생략하면, 스크립트의 작업 디렉토리가 (A_WorkingDir) 사용됩니다.

Options

If omitted, the command launches Target normally and shows a warning dialog whenever Target could not be launched. To change this behavior, specify one or more of the following words:

Max: 최대화 기동

Min: 최소화 기등

Hide: 숨은 채로 기동 (위와 조합해 사용할 수 없습니다)

주의: 어떤 어플리케이션은 (예, Calc.exe) 요청한 기동 상태를 준수하지 않습니다. 그런 경우 Max/Min/Hide는 아무 효과가 없습니다.

UseErrorLevel: UseErrorLevel 홀로 지정하거나 위이 단어 중 하나에 추가해 지정할 수 있습니다 (다른 단어와는 스페이스로 구분합니다). 기동에 실패하면, 이 옵션은 경고 대화상자를 건너뛰고, ErrorLevel에 ERROR를 설정하며, 그리고 현재 쓰레드를 계속 진행합니다. 기동에 성공하면, RunWait는 ErrorLevel을 프로그램의 종료 코드에 설정하고, Run은 거기에 0을 설정합니다.

UseErrorLevel이 지정되면, 변수 A_LastError는 운영 체제의 GetLastError() 함수의 결과에 설정됩니다. A_LastError는 0부터 4294967295 사이의 숫자입니다 (언제나 십진수로 포맷됩니다. 십육진수로 포맷되지 않습니다). 영 (0)은 성공을 뜻하지만, 다른 숫자는 기동에 실패했다는 뜻입니다. 각 숫자는 특정한 에러 조건에 상당합니다 (목록은 www.microsoft.com에서 "시스템 에러 코드"를 검색해 보십시오). ErrorLevel처럼, A_LastError는 쓰레드마다 설정됩니다; 즉, 다른 쓰레드가 인터럽트 해도 변경되지 않습니다. 그렇지만, A_LastError는 DllCall()이 설정하기도 합니다.

OutputVarPID

The name of the output variable in which to store the newly launched program's unique Process ID (PID). PID를 결정할 수 없으면 변수는 비어 있습니다, 보통 그런 경우는 실행 파일 보다는 문맥 메뉴, 문서, 또는 단축 아이콘을 기동할 때 일어납니다. RunWait도 이 매개변수를 지원합니다. 그렇지만 그의 OutputVarPID는 반드시 또다른 메쏘드에서 점검해야 합니다 (그렇지 않으면, 다음 RunWait가 실행하는 줄에 도달할 즈음이면 프로세스가 종료되어 버리기 때문에 PID는 무효가 되어 버립니다).

Run 명령어가 PID를 실행한 후, 해당 프로세스가 만든 창은 아직 존재하지 않을 수 있습니다. 적어도 하나의 창은 만들어지기를 기다리려면, WinWait ahk_pid %OutputVarPID%를 사용하십시오.

에러 처리

[v1.1.04+]: 이 명령어는 실패하면 예외를 던질 수 있습니다. 더 자세한 정보는 실행시간 에러를 참조하십시오.

Run: (위의) UseErrorLevel이 효과가 없는 한, ErrorLevel을 설정하지 않습니다. 실패시 ErrorLevel은 단어 ERROR이 설정되고 성공하면 0이 설정됩니다.

RunWait: ErrorLevel을 프로그램의 종료 코드에 설정합니다 (부호있는 32-비트 정수). UseErrorLevel가 영향을 미치고 기동에 실패하면 단어 ERROR가 저장됩니다.

논평

Run과 다르게, RunWait는 Target이 종료하거나 끝날 때까지 기다립니다. 종료 시에 ErrorLevel이 프로그램의 종료 코드에 설정됩니다 (부호있는 32-비트 정수). 어떤 프로그램은 여전히 실행 중임에도 불구하고 즉시 반환되는 듯 보입니다; 이런 프로그램은 또다른 프로세스를 퍼트립니다.

If Target contains any commas, they must be escaped as highlighted three times in the following example:

Run rundll32.exe shell32.dll`,Control_RunDLL desk.cpl`,`, 3  ; 제어판 > 디스플레이 > 설정이 열립니다

ComSpec을 통하여 프로그램을 실행할 때 (cmd.exe) -- 아마도 프로그램의 입력이나 출력을 방향전환해야 할 필요가 있기 때문에 -- 실행 파일의 이름이나 경로에 스페이스가 포함되어 있으면, 전체 문자열을 바깥쪽에서 따옴표로 둘러 싸야 합니다. In the following example, the outer quotes are highlighted in yellow:

Run %ComSpec% /c ""C:\My Utility.exe" "param 1" "second param" >"C:\My File.txt""

Target을 기동할 수 없으면, 에러 창이 화면에 나타나고 현재 쓰레드는 종료합니다. 문자열 UseErrorLevel이 세 번째 매개변수에 포함되어 있거나 에러를 Try/Catch 서술문으로 잡는 경우는 예외로 합니다.

Target이 정확한 경로이면, 수행성능이 약간 개선될 수 있습니다. 예, Run, C:\My Documents\Test.txt 말고 Run, C:\Windows\Notepad.exe "C:\My Documents\Test.txt"으로 지정합니다.

특수한 CLSID 폴더는 Run을 통하여 열 수 있습니다. 예를 들어:

Run ::{20d04fe0-3aea-1069-a2d8-08002b30309d}  ; "내 컴퓨터" 폴더를 엽니다.
Run ::{645ff040-5081-101b-9f08-00aa002f954e}  ; 휴지통을 엽니다.

문맥 메뉴는 탐색창에서 파일에 우클릭하면 나타나는 조치들에 상응합니다. 파일이 문맥 메뉴 없이 기동하면, 기본 문맥 메뉴가 (보통 "open") 그 특정한 파일 유형에 대하여 사용됩니다. 지정하면, 문맥 메뉴는 목표 파일 이름 다음에 따라와야 합니다. 현재 다음 문맥 메뉴를 지원합니다:

Verb 설명
*verb [AHK_L 57+]: 시스템에-정의된 또는 맞춤 문맥 메뉴. 예를 들어: Run *Compile %A_ScriptFullPath%. 윈도우즈 비스타 이후에서, *RunAs 문맥 메뉴를 Run as administrator 우클릭 메뉴 항목 대신에 사용할 수 있습니다.
properties

지시한 파일에 대하여 탐색기의 특성 창을 보여줍니다. 예를 들어: Run, properties "C:\My File.txt"

주의: 특성 창은 스크립트가 종료할 때 자동으로 닫힙니다. 이를 피하려면, WinWait를 사용해 창이 나타나기를 기다린 다음, WinWaitClose를 사용해 사용자가 닫기를 기다리십시오.

find 지시된 폴더에 대하여 탐색기의 파일 검색 또는 찾기 창의 실체를 엽니다. 예를 들어: Run, find D:\
explore 지시된 폴더에 탐색기의 실체를 엽니다. 예를 들어: Run, explore %A_ProgramFiles%.
edit 지시된 파일을 편집을 위해 엽니다. 지시된 파일의 유형에 "edit" 조치가 연관되어 있지 않으면 작동하지 않을 수도 있습니다. 예를 들어: Run, edit "C:\My File.txt"
open 지시된 파일을 엽니다 (보통 필요하지 않습니다. 대부분의 파일 유형에 기본 조치이기 때문입니다). 예를 들어: Run, open "My File.txt".
print 지시된 파일을 연관된 어플리케이션으로 인쇄합니다. 예를 들어: Run, print "My File.txt"

RunWait가 대기 상태에 있는 동안, 새 쓰레드핫키, 맞춤 메뉴 항목, 또는 타이머를 통하여 기동할 수 있습니다.

Run as Administrator [AHK_L 57+]

For an executable file, the *RunAs verb is equivalent to selecting Run as administrator from the right-click menu of the file. For example, the following code attempts to restart the current script as admin:

full_command_line := DllCall("GetCommandLine", "str")

if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
    try
    {
        if A_IsCompiled
            Run *RunAs "%A_ScriptFullPath%" /restart
        else
            Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
    }
    ExitApp
}

MsgBox A_IsAdmin: %A_IsAdmin%`nCommand line: %full_command_line%

If the user cancels the UAC dialog or Run fails for some other reason, the script will simply exit.

Using /restart ensures that a single instance prompt is not shown if the new instance of the script starts before ExitApp is called.

If UAC is disabled, *RunAs will launch the process without elevating it. Checking for /restart in the command line ensures that the script does not enter a runaway loop in that case. Note that /restart is a built-in switch, so is not included in the array of command-line parameters.

The example can be modified to fit the script's needs:

[v1.0.92.01+]: If UAC is enabled, the AutoHotkey installer registers the RunAs verb for .ahk files, which allows Run *RunAs script.ahk to launch a script as admin with the default executable.

RunAs, Process, Exit, CLSID List, DllCall()

예제

Run is able to launch Windows system programs from any directory. Note that executable file extensions such as .exe can be omitted.

Run, notepad

Run is able to launch URLs:

The following opens an internet address in the user's default web browser.

Run, https://www.google.com

The following opens the default e-mail application with the recipient filled in.

Run, mailto:someone@somedomain.com

The following does the same as above, plus the subject and body.

Run, mailto:someone@somedomain.com?subject=This is the subject line&body=This is the message body's text.

Opens a document in a maximized application and displays a custom error message on failure.

Run, ReadMe.doc, , Max UseErrorLevel
if (ErrorLevel = "ERROR")
    MsgBox 문서를 기동할 수 없었습니다.

Runs the dir command in minimized state and stores the output in a text file. After that, the text file and its properties dialog will be opened.

#Persistent
RunWait, %ComSpec% /c dir C:\ >>C:\DirTest.txt, , Min
Run, C:\DirTest.txt
Run, properties C:\DirTest.txt

Run is able to launch CLSIDs:

The following opens the recycle bin.

Run, ::{645ff040-5081-101b-9f08-00aa002f954e}

The following opens the "My Computer" directory.

Run, ::{20d04fe0-3aea-1069-a2d8-08002b30309d}

여러 명령어를 연속적으로 실행하려면, 사이에 "&&"를 사용하십시오.

Run, %ComSpec% /c dir /b > C:\list.txt && type C:\list.txt && pause

The following functions can be used to run a command and retrieve its output or to run multiple commands in one go and retrieve their output.

MsgBox % RunWaitOne("dir " A_ScriptDir)

MsgBox % RunWaitMany("
(
echo 명령어는 여기에 배치합니다,
echo 하나씩 실행될 것이고,
echo 결국 출력을 얻게 될 것입니다.
)")

RunWaitOne(command) {
    ; WshShell 객체: http://msdn.microsoft.com/ko-kr/library/aew9yb99
    shell := ComObjCreate("WScript.Shell")
    ; cmd.exe를 통하여 명령어 하나를 실행합니다.
    exec := shell.Exec(ComSpec " /C " command)
    ; 그 명령어의 출력을 읽어 돌려줍니다
    return exec.StdOut.ReadAll()
}

RunWaitMany(commands) {
    shell := ComObjCreate("WScript.Shell")
    ; 명령어 반향을 끄고 cmd.exe를 엽니다
    exec := shell.Exec(ComSpec " /Q /K echo off")
    ; 실행할 명령어를 새줄문자로 갈라서 전송합니다.
    exec.StdIn.WriteLine(commands "`nexit")  ; 언제나 결국 종료합니다!
    ; 모든 명령어의 출력을 읽어 돌려줍니다.
    return exec.StdOut.ReadAll()
}

주어진 코드를 새 AutoHotkey 프로세스로 실행합니다.

ExecScript(Script, Wait:=true)
{
    shell := ComObjCreate("WScript.Shell")
    exec := shell.Exec("AutoHotkey.exe /ErrorStdOut *")
    exec.StdIn.Write(script)
    exec.StdIn.Close()
    if Wait
        return exec.StdOut.ReadAll()
}

; 예제:
InputBox expr,, 새 스크립트로 평가할 표현식을 입력하십시오.,,,,,,,, Asc("*")
result := ExecScript("FileAppend % (" expr "), *")
MsgBox % "Result: " result