Меню

Ошибка ахк the script contains syntax error

Possible Errors

(0x00+) General

  • (0x0) Compilation was successful.
  • (0x1) Error: Unknown error.
  • (0x2) Compilation was cancelled.
  • (0x3) Error: Bad parameters

(0x10+) Syntax

  • (0x1) Error: The script contains syntax errors.
  • (0x2) Error: Invalid «FileInstall» syntax found. Note that the first parameter must not be specified using a continuation section.

(0x20+) Not supported & AutoHotkey version dependent

  • (0x1) Error: #DerefChar is not supported.
  • (0x2) Error: #Delimiter is not supported.
  • (0x3) Error: /NoDecompile is not supported.
  • (0x4) Error: Password protection is not supported.
  • (0x5) Error: The AutoHotkey build used for auto-inclusion of library functions is not recognized.
  • (0x6) Error: Legacy AutoHotkey versions (prior to v1.1) can not be used to do auto-inclusion of library functions.
  • (0x7) Error: Cursor resource adding is not supported yet.

(0x30+) File open & Not found

  • (0x1) Error: Error opening the destination file.
  • (0x2) Script or #include cannot be opened.
  • (0x3) Error: Source file not specified.
  • (0x4) Error: The selected Base file does not exist.
  • (0x5) Error changing icon: File does not exist.
  • (0x6) Error: Specified resource does not exist.

(0x40+) File write

  • (0x1) Error: Unable to copy Base file to destination.
  • (0x2) Error changing icon: Unable to read icon or icon was of the wrong format.
  • (0x3) Error adding script file
  • (0x4) Error adding FileInstall file
  • (0x5) Error: Could not move final compiled binary file to destination.
  • (0x6) Error adding resource.

(0x50+) Miscellaneous

  • (0x1) Call to AutoHotkey has failed, Error code is n
  • (0x2) Error: Cannot find AutoHotkey help file!
  • (0x3) Error: Invalid codepage parameter was given.
  • (0x4) Error: Cannot determine AutoHotkey vintage.

(0x60+) Compiler directives

  • (0x1) Could not change executable subsystem.
  • (0x2) Command failed with RC=n.
  • (0x3) Error: Invalid directive.
  • (0x4) Error: Wrongly formatted directive.
  • (0x5) Error: Resource language must be an integer between 0 and 0xFFFF.
  • (0x6) Error: Impossible BMP file.
  • (0x7) Error changing the version information.
  • (0x8) Error: ‘Obey’ directive cannot be executed.

Hi guys,

I’ve got plenty of problems trying to make a script work. And at this stage need your help and eye balls to point out whatever I’m doing wrong.

I wanted to use some functionality only available in AHK V2.

I’m tearing my hair out, as as far as my eyes can tell, the syntax is exactly the same as in the AHK V2 documentation, but if I try to compile the script it says that the script contains errors:

1) WinGetCont

Error: The script contains syntax errors.

Specifically:
C:DropboxGTD portableMindMapdualmindmapper.ahk (74) : ==> Call to nonexistent function.

Specifically: WinGetCount(«WorkFlowy»)

But the documentation here:
https lexikos.github.io /v2/docs/commands/WinGetCount.htm Broken Link for safety
says:
Count := WinGetCount(WinTitle, WinText, ExcludeTitle, ExcludeText)

and I wrote:
WINDOWZ := WinGetCount(«WorkFlowy»)

2) SendMode Input

C:DropboxGTD portableMindMapdualmindmapper.ahk (13) : ==> Call to nonexistent function.
Specifically: SendMode(«Input»)

but the doc https lexikos.github.io /v2/docs/commands/SendMode.htm Broken Link for safety says:
SendMode «Input»

And I wrote
SendMode «Input»

3) SetTitleMatchMode(«RegEx») or SetTitleMatchMode RegEx
C:DropboxGTD portableMindMapdualmindmapper.ahk (141) : ==> Parameter #1 invalid.
Specifically: «RegEx»

The documentation https lexikos.github.io /v2/docs/commands/SetTitleMatchMode.htm Broken Link for safety says:
SetTitleMatchMode «RegEx»

I wrote
SetTitleMatchMode «RegEx»

If you want the whole source code, here it is: https www.dropbox.com /s/ypbx7148uo2kowt/dualmindmapper.ahk?dl=0 Broken Link for safety

Please, I would seriously appreciate ya’lls help.

home icon
Все разделы

comunity icon
Нужна помощь?

Выводит сообщения о синтаксических ошибках, препятствующих запуску скрипта, в стандартный вывод, а не в диалоговое окно.

#ErrorStdOut

Эта возможность позволяет продвинутым редакторам, таким как Textpad, Scite, Crimson и EditPlus, переходить к ошибочной строке, когда встречается синтаксическая ошибка. Поскольку эту директиву пришлось бы добавлять в каждый скрипт, обычно лучше настроить ваш редактор на использование ключа командной строки /ErrorStdOut при запуске любого скрипта AutoHotkey (смотрите ниже инструкции по настройке).

Хотя синтаксические ошибки посылаются в стандартный вывод (stdout), они не появятся прямо в окне командной строки. Вместо этого такой вывод может быть захвачен через конвейеризацию или перенаправление. Например:

«C:Program FilesAutoHotkeyAutoHotkey.exe» /ErrorStdOut «My Script.ahk»|more
«C:Program FilesAutoHotkeyAutoHotkey.exe» /ErrorStdOut «My Script.ahk» >»Syntax-Error Log.txt»

Вы также сможете направлять вывод по конвейеру в буфер обмена, если скачаете cb.zip (4 Кб) и будете следовать этому примеру:

«C:Program FilesAutoHotkeyAutoHotkey.exe» /ErrorStdOut «My Script.ahk» |cb.exe

Инструкции для отдельных редакторов

EditPlus

:

  • В строке меню выберите Tools > Configure User Tools.
  • Нажмите кнопку Add Tool > Program.
  • Menu Text: По вашему выбору.
  • Command: C:Program FilesAutoHotkeyAutoHotkey.exe
  • Argument: /ErrorStdOut «$(FilePath)»
  • Initial directory: $(FileDir)
  • Capture output: Yes

TextPad

:

  • В строке меню выберите Configure > Preferences.
  • Разверните пункт Tools.
  • Нажмите кнопку Add и выберите «Program».
  • Скопируйте и вставьте (исправьте на ваш путь): C:WindowsSystem32cmd.exe
  • Нахмите OK.
  • Трижды щёлкните вновь добавленный пункт (cmd.exe) в окне списка и переименуйте по вашему выбору (например, Launch Script).
  • Нажмите Apply.
  • Выберите новый пункт в дереве слева и введите следующую информацию:
  • Command (должно уже быть заполнено): cmd.exe (или полный путь к нему)
  • Parameters (исправьте на ваш путь, если необходимо): /c «»C:Program FilesAutoHotkeyAutoHotkey.exe» /ErrorStdOut «$File»»
  • Initial folder: $FileDir
  • Отметьте следующие флажки: 1) Run minimized; 2) Capture output.
  • Нажмите OK. Вновь добавленный пункт теперь должен быть в меню Tools.

Пример

#ErrorStdOut

Автор перевода: YMP

Настоящее имя переводчика: Юрий Попов

SyntaxError — это ошибка, которая легко может ввести в ступор начинающего программиста. Стоит забыть одну запятую или не там поставить кавычку и Python наотрез откажется запускать программу. Что ещё хуже, по выводу в консоль сложно сообразить в чём дело. Выглядят сообщения страшно и непонятно. Что с этим делать — не ясно. Вот неполный список того, что можно встретить:

  • SyntaxError: invalid syntax
  • SyntaxError: EOL while scanning string literal
  • SyntaxError: unexpected EOF while parsing

Эта статья о том, как справиться с синтаксической ошибкой SyntaxError. Дочитайте её до конца и получите безотказный простой алгоритм действий, что поможет вам в трудную минуту — ваш спасательный круг.

Работать будем с программой, которая выводит на экран список учеников. Её код выглядит немного громоздко и, возможно, непривычно. Если не всё написанное вам понятно, то не отчаивайтесь, чтению статьи это не помешает.


students = [
    ['Егор', 'Кузьмин'],
    ['Денис', 'Давыдов'],
]

for first_name, last_name in students:
    label = 'Имя ученика: {first_name} {last_name}'.format(
        first_name = first_name
        last_name = last_name
    )

    print(label)

Ожидается примерно такой результат в консоли:

$ python script.py
Имя ученика: Егор Кузьмин
Имя ученика: Денис Давыдов

Но запуск программы приводит к совсем другому результату. Скрипт сломан:

$ python script.py
  File "script.py", line 9
    last_name = last_name
            ^
SyntaxError: invalid syntax

Ошибки в программе бывают разные и каждой нужен свой особый подход. Первым делом внимательно посмотрите на вывод программы в консоль. На последней строчке написано SyntaxError: invalid syntax. Если эти слова вам не знакомы, то обратитесь за переводом к Яндекс.Переводчику:

SyntaxError: недопустимый синтаксис
SyntaxError: неверный синтаксис

Первое слово SyntaxError Яндекс не понял. Помогите ему и разделите слова пробелом:

Syntax Error: invalid syntax
Синтаксическая ошибка: неверный синтаксис

Теория. Синтаксические ошибки

Программирование — это не магия, а Python — не волшебный шар. Он не умеет предсказывать будущее, у него нет доступа к секретным знаниями, это просто автомат, это программа. Узнайте как она работает, как ищет ошибки в коде, и тогда легко найдете эффективный способ отладки. Вся необходимая теория собрана в этом разделе, дочитайте до конца.

SyntaxError — это синтаксическая ошибка. Она случается очень рано, еще до того, как Python запустит программу. Вот что делает компьютер, когда вы запускаете скрипт командой python script.py:

  1. запускает программу python
  2. python считывает текст из файла script.py
  3. python превращает текст программы в инструкции
  4. python исполняет инструкции

Синтаксическая ошибка SyntaxError возникает на четвёртом этапе в момент, когда Python разбирает текст программы на понятные ему компоненты. Сложные выражения в коде он разбирает на простейшие инструкции. Вот пример кода и инструкции для него:

person = {'name': 'Евгений'}

Инструкции:

  1. создать строку 'Евгений'
  2. создать словарь
  3. в словарь добавить ключ 'name' со значением 'Евгений'
  4. присвоить результат переменной person

SyntaxError случается когда Python не смог разбить сложный код на простые инструкции. Зная это, вы можете вручную разбить код на инструкции, чтобы затем проверить каждую из них по отдельности. Ошибка прячется в одной из инструкций.

1. Найдите поломанное выражение

Этот шаг сэкономит вам кучу сил. Найдите в программе сломанный участок кода. Его вам предстоит разобрать на отдельные инструкции. Посмотрите на вывод программы в консоль:

$ python script.py
  File "script.py", line 9
    last_name = last_name
            ^
SyntaxError: invalid syntax

Вторая строчка сообщает: File "script.py", line 9 — ошибка в файле script.py на девятой строчке. Но эта строка является частью более сложного выражения, посмотрите на него целиком:

label = 'Имя ученика: {first_name} {last_name}'.format(
    first_name = first_name
    last_name = last_name
)

2. Разбейте выражение на инструкции

В прошлых шагах вы узнали что сломан этот фрагмент кода:

label = 'Имя ученика: {first_name} {last_name}'.format(
    first_name = first_name
    last_name = last_name
)

Разберите его на инструкции:

  1. создать строку 'Имя ученика: {first_name} {last_name}'
  2. получить у строки метод format
  3. вызвать функцию с двумя аргументами
  4. результат присвоить переменной label

Так выделил бы инструкции программист, но вот Python сделать так не смог и сломался. Пора выяснить на какой инструкции нашла коса на камень.

Теперь ваша задача переписать код так, чтобы в каждой строке программы исполнялось не более одной инструкции из списка выше. Так вы сможете тестировать их по отдельности и облегчите себе задачу. Так выглядит отделение инструкции по созданию строки:

# 1. создать строку
template = 'Имя ученика: {first_name} {last_name}'

label = template.format(
    first_name = first_name
    last_name = last_name
)

Сразу запустите код, проверьте что ошибка осталась на прежнему месте. Приступайте ко второй инструкции:

# 1. создать строку
template = 'Имя ученика: {first_name} {last_name}'

# 2. получить у строки метод
format = template.format

label = format(
    first_name = first_name
    last_name = last_name
)

Строка format = template.format создает новую переменную format и кладёт в неё функцию. Да, да, это не ошибка! Python разрешает класть в переменные всё что угодно, в том числе и функции. Новая переменная переменная format теперь работает как обычная функция, и её можно вызвать: format(...).

Снова запустите код. Ошибка появится внутри format. Под сомнением остались две инструкции:

  1. вызвать функцию с двумя аргументами
  2. результат присвоить переменной label

Скорее всего, Python не распознал вызов функции. Проверьте это, избавьтесь от последней инструкции — от создания переменной label:

# 1. создать строку
template = 'Имя ученика: {first_name} {last_name}'

# 2. получить у строки метод
format = template.format

# 3. вызвать функцию
format(
    first_name = first_name
    last_name = last_name
)

Запустите код. Ошибка снова там же — внутри format. Выходит, код вызова функции написан с ошибкой, Python не смог его превратить в инструкцию.

3. Проверьте синтаксис вызова функции

Теперь вы знаете что проблема в коде, вызывающем функцию. Можно помедитировать еще немного над кодом программы, пройтись по нему зорким взглядом еще разок в надежде на лучшее. А можно поискать в сети примеры кода для сравнения.

Запросите у Яндекса статьи по фразе “Python синтаксис функции”, а в них поищите код, похожий на вызов format и сравните. Вот одна из первых статей в поисковой выдаче:

  • Функции в Python

Уверен, теперь вы нашли ошибку. Победа!

Scripts

Related topics:

  • Using the Program: How to use AutoHotkey, in general.
  • Concepts and Conventions: General explanation of various concepts utilised by AutoHotkey.
  • Scripting Language: Specific details about syntax (how to write scripts).

Table of Contents

  • Introduction
  • The Top of the Script (the Auto-execute Section): This portion executes automatically when the script starts.
  • Splitting a Long Line into a Series of Shorter Ones: This can improve a script’s readability and maintainability.
  • Convert a Script to an EXE (ahk2exe): Convert a .ahk script into a .exe file that can run on any PC.
  • Passing Command Line Parameters to a Script: The variables %1%, %2%, etc. contain the incoming parameters.
  • Script File Codepage: Using non-ASCII characters safely in scripts.
  • Debugging a Script: How to find the flaws in a misbehaving script.

Introduction

Each script is a plain text file containing lines to be executed by the program (AutoHotkey.exe). A script may also contain hotkeys and hotstrings, or even consist entirely of them. However, in the absence of hotkeys and hotstrings, a script will perform its commands sequentially from top to bottom the moment it is launched.

The program loads the script into memory line by line, and each line may be up to 16,383 characters long. During loading, the script is optimized and validated. Any syntax errors will be displayed, and they must be corrected before the script can run.

The Top of the Script (the Auto-execute Section)

After the script has been loaded, it begins executing at the top line, continuing until a Return, Exit, hotkey/hotstring label, or the physical end of the script is encountered (whichever comes first). This top portion of the script is referred to as the auto-execute section.

Note: While the script’s first hotkey/hotstring label has the same effect as return, other hotkeys and labels do not.

A script that is not persistent and that lacks hotkeys, hotstrings, OnMessage, and GUI will terminate after the auto-execute section has completed. Otherwise, it will stay running in an idle state, responding to events such as hotkeys, hotstrings, GUI events, custom menu items, and timers.

Every thread launched by a hotkey, hotstring, menu item, GUI event, or timer starts off fresh with the default values for the following attributes as set in the auto-execute section. If unset, the standard defaults will apply (as documented on each of the following pages): DetectHiddenWindows, DetectHiddenText, SetTitleMatchMode, SetBatchLines, SendMode, SetKeyDelay, SetMouseDelay,
SetWinDelay,
SetControlDelay,
SetDefaultMouseSpeed,
CoordMode,
SetStoreCapslockMode,
AutoTrim, SetFormat, StringCaseSense, Thread, and Critical.

If the auto-execute section takes a long time to complete (or never completes), the default values for the above settings will be put into effect after 100 milliseconds. When the auto-execute section finally completes (if ever), the defaults are updated again to be those that were in effect at the end of the auto-execute section. Thus, it’s usually best to make any desired changes to the defaults at the top of scripts that contain hotkeys, hotstrings, timers, or custom menu items. Also note that each thread retains its own collection of the above settings. Changes made to those settings will not affect other threads.

Splitting a Long Line into a Series of Shorter Ones

Long lines can be divided up into a collection of smaller ones to improve readability and maintainability. This does not reduce the script’s execution speed because such lines are merged in memory the moment the script launches.

Method #1: A line that starts with «and», «or», ||, &&, a comma, or a period is automatically merged with the line directly above it (in v1.0.46+, the same is true for all other expression operators except ++ and —). In the following example, the second line is appended to the first because it begins with a comma:

FileAppend, This is the text to append.`n   ; A comment is allowed here.
    , %A_ProgramFiles%SomeApplicationLogFile.txt  ; Comment.

Similarly, the following lines would get merged into a single line because the last two start with «and» or «or»:

if (Color = "Red" or Color = "Green"  or Color = "Blue"   ; Comment.
    or Color = "Black" or Color = "Gray" or Color = "White")   ; Comment.
    and ProductIsAvailableInColor(Product, Color)   ; Comment.

The ternary operator is also a good candidate:

ProductIsAvailable := (Color = "Red")
    ? false  ; We don't have any red products, so don't bother calling the function.
    : ProductIsAvailableInColor(Product, Color)

Although the indentation used in the examples above is optional, it might improve clarity by indicating which lines belong to ones above them. Also, it is not necessary to include extra spaces for lines starting with the words «AND» and «OR»; the program does this automatically. Finally, blank lines or comments may be added between or at the end of any of the lines in the above examples.

Method #2: This method should be used to merge a large number of lines or when the lines are not suitable for Method #1. Although this method is especially useful for auto-replace hotstrings, it can also be used with any command or expression. For example:

; EXAMPLE #1:
Var =
(
Line 1 of the text.
Line 2 of the text. By default, a linefeed (`n) is present between lines.
)

; EXAMPLE #2:
FileAppend,  ; The comma is required in this case.
(
A line of text.
By default, the hard carriage return (Enter) between the previous line and this one will be written to the file as a linefeed (`n).
    By default, the tab to the left of this line will also be written to the file (the same is true for spaces).
By default, variable references such as %Var% are resolved to the variable's contents.
), C:My File.txt

In the examples above, a series of lines is bounded at the top and bottom by a pair of parentheses. This is known as a continuation section. Notice that the bottom line contains FileAppend’s last parameter after the closing parenthesis. This practice is optional; it is done in cases like this so that the comma will be seen as a parameter-delimiter rather than a literal comma.

The default behavior of a continuation section can be overridden by including one or more of the following options to the right of the section’s opening parenthesis. If more than one option is present, separate each one from the previous with a space. For example: ( LTrim Join| %.

Join: Specifies how lines should be connected together. If this option is omitted, each line except the last will be followed by a linefeed character (`n). If the word Join is specified by itself, lines are connected directly to each other without any characters in between. Otherwise, the word Join should be followed immediately by as many as 15 characters. For example, Join`s would insert a space after each line except the last («`s» indicates a literal space — it is a special escape sequence recognized only by Join). Another example is Join`r`n, which inserts CR+LF between lines. Similarly, Join| inserts a pipe between lines. To have the final line in the section also ended by a join-string, include a blank line immediately above the section’s closing parenthesis.

Known limitation: If the Join string ends with a colon, it must not be the last option on the line. For example, (Join: is treated as the label «(Join» and (LTrim Join: is unsupported, but (Join: C is okay.

LTrim: Omits spaces and tabs at the beginning of each line. This is primarily used to allow the continuation section to be indented. Also, this option may be turned on for multiple continuation sections by specifying #LTrim on a line by itself. #LTrim is positional: it affects all continuation sections physically beneath it. The setting may be turned off via #LTrim Off.

RTrim0 (RTrim followed by a zero): Turns off the omission of spaces and tabs from the end of each line.

% (percent sign): Treats percent signs as literal rather than as variable references. This avoids the need to escape each percent sign to make it literal. This option is not needed in places where percent signs are already literal, such as auto-replace hotstrings.

, (comma): Treats commas as delimiters rather than as literal commas. This rarely-used option is necessary only for the commas between command parameters because in function calls, the type of comma does not matter. Also, this option transforms only those commas that actually delimit parameters. In other words, once the command’s final parameter is reached (or there are no parameters), subsequent commas are treated as literal commas regardless of this option.

` (accent): Treats each backtick character literally rather than as an escape character. This also prevents commas and percent signs from being explicitly and individually escaped. In addition, it prevents the translation of any explicitly specified escape sequences such as `r and `t.

) [v1.1.01+]: If a closing parenthesis appears in the continuation section’s options (except as a parameter of the Join option), the line is reinterpreted as an expression instead of the beginning of a continuation section. This allows expressions like (x.y)[z]() to work without the need to escape the opening parenthesis.

Remarks

Escape sequences such as `n (linefeed) and `t (tab) are supported inside the continuation section except when the accent (`) option has been specified.

When the comment option is absent, semicolon and /*..*/ comments are not supported within the interior of a continuation section because they are seen as literal text. However, comments can be included on the bottom and top lines of the section. For example:

FileAppend,   ; Comment.
; Comment.
( LTrim Join    ; Comment.
     ; This is not a comment; it is literal. Include the word Comments in the line above to make it a comment.
), C:File.txt   ; Comment.

As a consequence of the above, semicolons never need to be escaped within a continuation section.

A continuation section cannot produce a line whose total length is greater than 16,383 characters (if it tries, the program will alert you the moment the script is launched). One way to work around this is to do a series of concatenations into a variable. For example:

Var =
(
...
)
Var = %Var%`n  ; Add more text to the variable via another continuation section.
(
...
)
FileAppend, %Var%, C:My File.txt

Since a closing parenthesis indicates the end of a continuation section, to have a line start with literal closing parenthesis, precede it with an accent/backtick: `).

A continuation section can be immediately followed by a line containing the open-parenthesis of another continuation section. This allows the options mentioned above to be varied during the course of building a single line.

The piecemeal construction of a continuation section by means of #Include is not supported.

Convert a Script to an EXE (ahk2exe)

A script compiler (courtesy of fincs) is included with the program.

Once a script is compiled, it becomes a standalone executable; that is, AutoHotkey.exe is not required in order to run the script. The compilation process creates an executable file which contains the following: the AutoHotkey interpreter, the script, any files it includes, and any files it has incorporated via the FileInstall command.

Ahk2Exe can be used in the following ways:

  1. GUI Interface: Run the «Convert .ahk to .exe» item in the Start Menu.
  2. Right-click: Within an open Explorer window, you can right-click any .ahk file and select «Compile Script» (only available if the script compiler option was chosen when AutoHotkey was installed). This creates an EXE file of the same base filename as the script, which appears after a short time in the same directory. Note: The EXE file is produced using the same custom icon, .bin file and use MPRESS setting that were last used by Method #1 above.
  3. Command Line: The compiler can be run from the command line with the following parameters:
    Ahk2Exe.exe /in MyScript.ahk [/out MyScript.exe] [/icon MyIcon.ico] [/bin AutoHotkeySC.bin] [/mpress 0or1]

    For example:

    Ahk2Exe.exe /in "MyScript.ahk" /icon "MyIcon.ico"

    Usage:

    • Parameters containing spaces should be enclosed in double quotes.
    • If the «out» file is omitted, the EXE will have the same base filename as the script itself.

Notes:

  • Compiling does not typically improve the performance of a script.
  • As of v1.1.01, password protection and the /NoDecompile switch are not supported.
  • The commands #NoTrayIcon and «Menu, Tray, ShowMainWindow» affect the behavior of compiled scripts.
  • Custom version info (as seen in Explorer’s file-properties dialog) can be added to your compiled scripts by using a utility such as Resource Hacker (freeware) to edit the file «AutoHotkeySC.bin». This file is contained in the «Compiler» subfolder where AutoHotkey was installed. Compile_AHK II can be used to facilitate this process. As of v1.1.01, the compiled script can be edited instead of AutoHotkeySC.bin.
  • The method above can also be used to change existing icons or add new ones to all compiled scripts.
  • The built-in variable A_IsCompiled contains 1 if the script is running in compiled form. Otherwise, it is blank.
  • When parameters are passed to Ahk2Exe, a message indicating the success or failure of the compiling process is written to stdout. Although the message will not appear at the command prompt, it can be «caught» by means such as redirecting output to a file. [v1.0.43+]
  • Additionally in the case of a failure, Ahk2Exe has exit codes indicating the kind of error that occurred. These error codes can be found at GitHub (ErrorCodes.md). [v1.1.22.03+]

The compiler’s source code and newer versions can be found at GitHub.

Compressing Compiled Scripts

Ahk2Exe optionally uses MPRESS (a freeware program by MATCODE Software) to compress compiled scripts. If mpress.exe is present in the «Compiler» subfolder where AutoHotkey was installed, it is used automatically unless it is disabled via /mpress 0 or the GUI setting.

Official website (was offline in March 2016): http://www.matcode.com/mpress.htm

Mirror (downloads and information): https://autohotkey.com/mpress/

Note: While compressing the script executable prevents casual inspection of the script’s source code using a plain text editor like Notepad or a PE resource editor, it does not prevent the source code from being extracted by tools dedicated to that purpose.

Passing Command Line Parameters to a Script

Scripts support command line parameters. The format is:

AutoHotkey.exe [Switches] [Script Filename] [Script Parameters]

And for compiled scripts, the format is:

CompiledScript.exe [Switches] [Script Parameters]

Switches: Zero or more of the following:

Switch Meaning Works compiled?
/f or /force Launch unconditionally, skipping any warning dialogs. This has the same effect as #SingleInstance Off. Yes
/r or /restart Indicate that the script is being restarted (this is also used by the Reload command, internally). Yes
/ErrorStdOut Send syntax errors that prevent a script from launching to stderr rather than displaying a dialog. See #ErrorStdOut for details. This can be combined with /iLib to validate the script without running it. Yes
/Debug [AHK_L 11+]: Connect to a debugging client. For more details, see Interactive Debugging. No
/CPn [AHK_L 51+]: Overrides the default codepage used to read script files. For more details, see Script File Codepage. No
/iLib «OutFile»

[v1.0.47+]: AutoHotkey loads the script but does not run it. For each script file which is auto-included via the library mechanism, two lines are written to the file specified by OutFile. These lines are written in the following format, where LibDir is the full path of the Lib folder and LibFile is the filename of the library:

#Include LibDir
#IncludeAgain LibDirLibFile.ahk

If the output file exists, it is overwritten. OutFile can be * to write the output to stdout.

If the script contains syntax errors, the output file may be empty. The process exit code can be used to detect this condition; if there is a syntax error, the exit code is 2. The /ErrorStdOut switch can be used to suppress or capture the error message.

No

Script Filename: This can be omitted if there are no Script Parameters. If omitted (such as if you run AutoHotkey directly from the Start menu), the program looks for a script file called AutoHotkey.ahk in the following locations, in this order:

  • The directory which contains the AutoHotkey executable.
  • The current user’s Documents folder.

The filename AutoHotkey.ahk depends on the name of the executable used to run the script. For example, if you rename AutoHotkey.exe to MyScript.exe, it will attempt to find MyScript.ahk. If you run AutoHotkeyU32.exe without parameters, it will look for AutoHotkeyU32.ahk.

Note: In old versions prior to revision 51, the program looked for AutoHotkey.ini in the working directory or AutoHotkey.ahk in My Documents.

[v1.1.17+]: Specify an asterisk (*) for the filename to read the script text from standard input (stdin). For an example, see ExecScript().

Script Parameters: The string(s) you want to pass into the script, with each separated from the next by a space. Any parameter that contains spaces should be enclosed in quotation marks. A literal quotation mark may be passed in by preceding it with a backslash («). Consequently, any trailing slash in a quoted parameter (such as «C:My Documents«) is treated as a literal quotation mark (that is, the script would receive the string C:My Documents«). To remove such quotes, use StringReplace, 1, 1, ",, All.

[v1.1.27+]: Incoming parameters, if present, are stored as an array in the built-in variable A_Args, and can be accessed using array syntax. A_Args[1] contains the first parameter. The following example exits the script when too few parameters are passed to it:

if A_Args.Length() < 3
{
    MsgBox % "This script requires at least 3 parameters but it only received " A_Args.Length() "."
    ExitApp
}

If the number of parameters passed into a script varies (perhaps due to the user dragging and dropping a set of files onto a script), the following example can be used to extract them one by one:

for n, param in A_Args  ; For each parameter:
{
    MsgBox Parameter number %n% is %param%.
}

If the parameters are file names, the following example can be used to convert them to their case-corrected long names (as stored in the file system), including complete/absolute path:

for n, GivenPath in A_Args  ; For each parameter (or file dropped onto a script):
{
    Loop Files, %GivenPath%, FD  ; Include files and directories.
        LongPath := A_LoopFileFullPath
    MsgBox The case-corrected long path name of file`n%GivenPath%`nis:`n%LongPath%
}

Known limitation: dragging files onto a .ahk script may fail to work properly if 8-dot-3 (short) names have been turned off in an NTFS file system. One work-around is to compile the script then drag the files onto the resulting EXE.

Legacy: The command line parameters are also stored in the variables %1%, %2%, and so on, as in versions prior to [v1.1.27]. In addition, %0% contains the number of parameters passed (0 if none). However, these variables cannot be referenced directly in an expression because they would be seen as numbers rather than variables. The following example exits the script when too few parameters are passed to it:

if 0 < 3  ; The left side of a non-expression if-statement is always the name of a variable.
{
    MsgBox This script requires at least 3 incoming parameters but it only received %0%.
    ExitApp
}

If the number of parameters passed into a script varies (perhaps due to the user dragging and dropping a set of files onto a script), the following example can be used to extract them one by one:

Loop, %0%  ; For each parameter:
{
    param := %A_Index%  ; Fetch the contents of the variable whose name is contained in A_Index.
    MsgBox, 4,, Parameter number %A_Index% is %param%.  Continue?
    IfMsgBox, No
        break
}

If the parameters are file names, the following example can be used to convert them to their case-corrected long names (as stored in the file system), including complete/absolute path:

Loop %0%  ; For each parameter (or file dropped onto a script):
{
    GivenPath := %A_Index%  ; Fetch the contents of the variable whose name is contained in A_Index.
    Loop %GivenPath%, 1
        LongPath = %A_LoopFileLongPath%
    MsgBox The case-corrected long path name of file`n%GivenPath%`nis:`n%LongPath%
}

Script File Codepage [AHK_L 51+]

The characters a script file may contain are restricted by the codepage used to load the file.

  • If the file begins with a UTF-8 or UTF-16 (LE) byte order mark, the appropriate codepage is used and the /CPn switch is ignored.
  • If the /CPn switch is passed on the command-line, codepage n is used. For a list of valid numeric codepage identifiers, see MSDN.
  • In all other cases, the system default ANSI codepage is used.

Note that this applies only to script files loaded by AutoHotkey, not to file I/O within the script itself. FileEncoding controls the default encoding of files read or written by the script, while IniRead and IniWrite always deal in UTF-16 or ANSI.

As all text is converted (where necessary) to the native string format, characters which are invalid or don’t exist in the native codepage are replaced with a placeholder: ANSI ‘?’ or Unicode ‘�’. In Unicode builds, this should only occur if there are encoding errors in the script file or the codepages used to save and load the file don’t match.

RegWrite may be used to set the default for scripts launched from Explorer (e.g. by double-clicking a file):

; Uncomment the appropriate line below or leave them all commented to
;   reset to the default of the current build.  Modify as necessary:
; codepage = 0        ; System default ANSI codepage
; codepage = 65001    ; UTF-8
; codepage = 1200     ; UTF-16
; codepage = 1252     ; ANSI Latin 1; Western European (Windows)
if (codepage != "")
    codepage := " /CP" . codepage
cmd="%A_AhkPath%"%codepage% "`%1" `%*
key=AutoHotkeyScriptShellOpenCommand
if A_IsAdmin    ; Set for all users.
    RegWrite, REG_SZ, HKCR, %key%,, %cmd%
else            ; Set for current user only.
    RegWrite, REG_SZ, HKCU, SoftwareClasses%key%,, %cmd%

This assumes AutoHotkey has already been installed. Results may be less than ideal if it has not.

Debugging a Script

Commands such as ListVars and Pause can help you debug a script. For example, the following two lines, when temporarily inserted at carefully chosen positions, create «break points» in the script:

ListVars
Pause

When the script encounters these two lines, it will display the current contents of all variables for your inspection. When you’re ready to resume, un-pause the script via the File or Tray menu. The script will then continue until reaching the next «break point» (if any).

It is generally best to insert these «break points» at positions where the active window does not matter to the script, such as immediately before a WinActivate command. This allows the script to properly resume operation when you un-pause it.

The following commands are also useful for debugging: ListLines, KeyHistory, and OutputDebug.

Some common errors, such as typos and missing «global» declarations, can be detected by enabling warnings.

Interactive Debugging [AHK_L 11+]

Interactive debugging is possible with a supported DBGp client. Typically the following actions are possible:

  • Set and remove breakpoints on lines — pause execution when a breakpoint is reached.
  • Step through code line by line — step into, over or out of functions and subroutines.
  • Inspect all variables or a specific variable.
  • View the stack of running subroutines and functions.

Note that this functionality is disabled for compiled scripts.

To enable interactive debugging, first launch a supported debugger client then launch the script with the /Debug command-line switch.

AutoHotkey.exe /Debug[=SERVER:PORT] ...

SERVER and PORT may be omitted. For example, the following are equivalent:

AutoHotkey /Debug "myscript.ahk"
AutoHotkey /Debug=localhost:9000 "myscript.ahk"

[AHK_L 59+]: To attach the debugger to a script which is already running, send it a message as shown below:

ScriptPath = ; SET THIS TO THE FULL PATH OF THE SCRIPT
DetectHiddenWindows On
ifWinExist %ScriptPath% ahk_class AutoHotkey
    ; Optional parameters:
    ;   wParam  = the IPv4 address of the debugger client, as a 32-bit integer.
    ;   lParam  = the port which the debugger client is listening on.
    PostMessage DllCall("RegisterWindowMessage", "str", "AHK_ATTACH_DEBUGGER")

Once the debugger client is connected, it may detach without terminating the script by sending the «detach» DBGp command.

Script Showcase

See this page for some useful scripts.

Здравствуйте. Возникла в проблема в написании простенького кода. Планировал заменить в определенной программе сочетаний клавиш «ctrl+alt» на «Xbutton2» , но что-то не получилось. Не могли б Вы, объяснить в чем я допустил ошибку

Screenshot 2021-06-14 083811.png
Screenshot 2021-06-14 083811.png 7.47 kb, file has never been downloaded.

You don’t have the permssions to download the attachments of this post.

  • Рейтинг : [ 813 | 0 ]

    Re: AHK:Помогите разобраться в ошибке.The script contains syntax errors.

    Publipor, ознакомьтесь, пожалуйста, с правилами форума. Обратите внимание на оформление заголовков и кода. Отредактируйте свой пост.

    Источник

    Scripts

    • Using the Program: How to use AutoHotkey, in general.
    • Concepts and Conventions: General explanation of various concepts utilised by AutoHotkey.
    • Scripting Language: Specific details about syntax (how to write scripts).

    Table of Contents

    • Introduction
    • The Top of the Script (the Auto-execute Section): This portion executes automatically when the script starts.
    • Splitting a Long Line into a Series of Shorter Ones: This can improve a script’s readability and maintainability.
    • Convert a Script to an EXE (Ahk2Exe): Convert a .ahk script into a .exe file that can run on any PC.
    • Passing Command Line Parameters to a Script: The variables %1%, %2%, etc. contain the incoming parameters.
    • Script File Codepage: Using non-ASCII characters safely in scripts.
    • Debugging a Script: How to find the flaws in a misbehaving script.

    Introduction

    Each script is a plain text file containing lines to be executed by the program (AutoHotkey.exe). A script may also contain hotkeys and hotstrings, or even consist entirely of them. However, in the absence of hotkeys and hotstrings, a script will perform its commands sequentially from top to bottom the moment it is launched.

    The program loads the script into memory line by line, and each line may be up to 16,383 characters long. During loading, the script is optimized and validated. Any syntax errors will be displayed, and they must be corrected before the script can run.

    The Top of the Script (the Auto-execute Section)

    After the script has been loaded, it begins executing at the top line, continuing until a Return, Exit, hotkey/hotstring label, or the physical end of the script is encountered (whichever comes first). This top portion of the script is referred to as the auto-execute section.

    Note: While the script’s first hotkey/hotstring label has the same effect as return, other hotkeys and labels do not.

    If the script is not persistent, it will terminate after the auto-execute section has completed. Otherwise, it will stay running in an idle state, responding to events such as hotkeys, hotstrings, GUI events, custom menu items, and timers. A script is automatically persistent if it contains hotkeys, hotstrings, OnMessage() or GUI, and in a few other cases. The #Persistent directive can also be used to explicitly make the script persistent.

    If the auto-execute section takes a long time to complete (or never completes), the default values for the above settings will be put into effect after 100 milliseconds. When the auto-execute section finally completes (if ever), the defaults are updated again to be those that were in effect at the end of the auto-execute section. Thus, it’s usually best to make any desired changes to the defaults at the top of scripts that contain hotkeys, hotstrings, timers, or custom menu items. Also note that each thread retains its own collection of the above settings. Changes made to those settings will not affect other threads.

    Splitting a Long Line into a Series of Shorter Ones

    Long lines can be divided up into a collection of smaller ones to improve readability and maintainability. This does not reduce the script’s execution speed because such lines are merged in memory the moment the script launches.

    Method #1: A line that starts with «and», «or», ||, &&, a comma, or a period is automatically merged with the line directly above it (in v1.0.46+, the same is true for all other expression operators except ++ and —). In the following example, the second line is appended to the first because it begins with a comma:

    Similarly, the following lines would get merged into a single line because the last two start with «and» or «or»:

    The ternary operator is also a good candidate:

    Although the indentation used in the examples above is optional, it might improve clarity by indicating which lines belong to ones above them. Also, it is not necessary to include extra spaces for lines starting with the words «AND» and «OR»; the program does this automatically. Finally, blank lines or comments may be added between or at the end of any of the lines in the above examples.

    Method #2: This method should be used to merge a large number of lines or when the lines are not suitable for Method #1. Although this method is especially useful for auto-replace hotstrings, it can also be used with any command or expression. For example:

    In the examples above, a series of lines is bounded at the top and bottom by a pair of parentheses. This is known as a continuation section. Notice that the bottom line contains FileAppend’s last parameter after the closing parenthesis. This practice is optional; it is done in cases like this so that the comma will be seen as a parameter-delimiter rather than a literal comma.

    The default behavior of a continuation section can be overridden by including one or more of the following options to the right of the section’s opening parenthesis. If more than one option is present, separate each one from the previous with a space. For example: ( LTrim Join| % .

    Join: Specifies how lines should be connected together. If this option is omitted, each line except the last will be followed by a linefeed character (`n). If the word Join is specified by itself, lines are connected directly to each other without any characters in between. Otherwise, the word Join should be followed immediately by as many as 15 characters. For example, Join`s would insert a space after each line except the last («`s» indicates a literal space — it is a special escape sequence recognized only by Join). Another example is Join`r`n , which inserts CR+LF between lines. Similarly, Join| inserts a pipe between lines. To have the final line in the section also ended by a join-string, include a blank line immediately above the section’s closing parenthesis.

    Known limitation: If the Join string ends with a colon, it must not be the last option on the line. For example, (Join: is treated as the label «(Join» and (LTrim Join: is unsupported, but (Join: C is okay.

    LTrim: Omits spaces and tabs at the beginning of each line. This is primarily used to allow the continuation section to be indented. Also, this option may be turned on for multiple continuation sections by specifying #LTrim on a line by itself. #LTrim is positional: it affects all continuation sections physically beneath it. The setting may be turned off via #LTrim Off .

    RTrim0 (RTrim followed by a zero): Turns off the omission of spaces and tabs from the end of each line.

    Comments (or Comment or Com or C) [v1.0.45.03+] : Allows semicolon comments inside the continuation section (but not /*..*/ ). Such comments (along with any spaces and tabs to their left) are entirely omitted from the joined result rather than being treated as literal text. Each comment can appear to the right of a line or on a new line by itself.

    % (percent sign): Treats percent signs as literal rather than as variable references. This avoids the need to escape each percent sign to make it literal. This option is not needed in places where percent signs are already literal, such as auto-replace hotstrings.

    , (comma): Treats commas as delimiters rather than as literal commas. This rarely-used option is necessary only for the commas between command parameters because in function calls, the type of comma does not matter. Also, this option transforms only those commas that actually delimit parameters. In other words, once the command’s final parameter is reached (or there are no parameters), subsequent commas are treated as literal commas regardless of this option.

    ` (accent): Treats each backtick character literally rather than as an escape character. This also prevents commas and percent signs from being explicitly and individually escaped. In addition, it prevents the translation of any explicitly specified escape sequences such as `r and `t.

    ) [v1.1.01+] : If a closing parenthesis appears in the continuation section’s options (except as a parameter of the Join option), the line is reinterpreted as an expression instead of the beginning of a continuation section. This allows expressions like (x.y)[z]() to work without the need to escape the opening parenthesis.

    Escape sequences such as `n (linefeed) and `t (tab) are supported inside the continuation section except when the accent (`) option has been specified.

    When the comment option is absent, semicolon and /*..*/ comments are not supported within the interior of a continuation section because they are seen as literal text. However, comments can be included on the bottom and top lines of the section. For example:

    As a consequence of the above, semicolons never need to be escaped within a continuation section.

    A continuation section cannot produce a line whose total length is greater than 16,383 characters (if it tries, the program will alert you the moment the script is launched). One way to work around this is to do a series of concatenations into a variable. For example:

    Since a closing parenthesis indicates the end of a continuation section, to have a line start with literal closing parenthesis, precede it with an accent/backtick: `) .

    A continuation section can be immediately followed by a line containing the open-parenthesis of another continuation section. This allows the options mentioned above to be varied during the course of building a single line.

    The piecemeal construction of a continuation section by means of #Include is not supported.

    Convert a Script to an EXE (Ahk2Exe)

    A script compiler (courtesy of fincs, with additions by TAC109) is included with the program.

    Once a script is compiled, it becomes a standalone executable; that is, AutoHotkey.exe is not required in order to run the script. The compilation process creates an executable file which contains the following: the AutoHotkey interpreter, the script, any files it includes, and any files it has incorporated via the FileInstall command. [v1.1.33+]: Additional files can be included using compiler directives.

    Compiler Topics

    Running the Compiler

    Ahk2Exe can be used in the following ways:

    GUI Interface: Run the «Convert .ahk to .exe» item in the Start Menu. (After invoking the GUI, there may be a pause before the window is shown; see Background Information for more details.)

    Right-click: Within an open Explorer window, right-click any .ahk file and select «Compile Script» (only available if the script compiler option was chosen when AutoHotkey was installed). This creates an EXE file of the same base filename as the script, which appears after a short time in the same directory. Note: The EXE file is produced using the same custom icon, .bin file and compression setting that were last saved in Method #1 above, or as specified by any relevant compiler directive in the script.

    Command Line: The compiler can be run from the command line by using the parameters shown below. If any command line parameters are used, the script is compiled immediately unless /gui is used. All parameters are optional, except that there must be one /gui or /in parameter.

    Parameter pair Meaning
    /in script_name The path and name of the script to compile. This is mandatory if any other parameters are used, unless /gui is used.
    /out exe_name The pathname of the output .exe to be created. Default is the directorybase_name of the input file plus extension of .exe, or any relevant compiler directive in the script.
    /icon icon_name The icon file to be used. Default is the last icon saved in the GUI interface, or any SetMainIcon compiler directive in the script.
    /base file_name [v1.1.33.10+]: The base file to be used (a .bin file or in [v1.1.34+] an .exe file). Default is the last base file name saved in the GUI interface, or any Base compiler directive in the script.
    /resourceid name [v1.1.34+] : Assigns a non-standard resource ID to be used for the main script for compilations which use an .exe base file (see Embedded Scripts). Numeric resource IDs should consist of a hash sign (#) followed by a decimal number. Default is #1, or any ResourceID compiler directive in the script.
    /cp codepage [v1.1.23.01+]: Overrides the default codepage used to read script files. For a list of possible values, see Code Page Identifiers. Note that Unicode scripts should begin with a byte-order-mark (BOM), rendering the use of this parameter unnecessary.
    /compress n [v1.1.33+]: Compress the exe? 0 = no, 1 = use MPRESS if present, 2 = use UPX if present. Default is the last setting saved in the GUI interface.
    /gui [v1.1.33+]: Shows the GUI instead of immediately compiling. The other parameters can be used to override the settings last saved in the GUI. /in is optional in this case.
    /silent [verbose] [v1.1.33.10+]: Disables all message boxes and instead outputs errors to the standard error stream (stderr); or to the standard output stream (stdout) if stderr fails. Other messages are also output to stdout. Optionally enter the word verbose to output status messages to stdout as well.
    Deprecated:
    /ahk file_name
    [v1.1.33+]: The pathname of AutoHotkey.exe to be used as a utility when compiling the script.
    Deprecated:
    /mpress 0or1
    Compress the exe with MPRESS? 0 = no, 1 = yes. Default is the last setting used in the GUI interface.
    Deprecated:
    /bin file_name
    The .bin file to be used. Default is the last .bin file name saved in the GUI interface.
    • Parameters containing spaces must be enclosed in double quotes.
    • Compiling does not typically improve the performance of a script.
    • As of v1.1.01, password protection and the /NoDecompile switch are not supported.
    • The commands #NoTrayIcon and «Menu, Tray, MainWindow» affect the behavior of compiled scripts.
    • The built-in variable A_IsCompiled contains 1 if the script is running in compiled form. Otherwise, it is blank.
    • [v1.0.43+]: When parameters are passed to Ahk2Exe, a message indicating the success or failure of the compiling process is written to stdout. Although the message will not appear at the command prompt, it can be «caught» by means such as redirecting output to a file.
    • [v1.1.22.03+]: Additionally in the case of a failure, Ahk2Exe has exit codes indicating the kind of error that occurred. These error codes can be found at GitHub (ErrorCodes.md).

    The compiler’s source code and newer versions can be found at GitHub.

    Base Executable File

    Each compiled script .exe is based on an executable file which implements the interpreter. The base files included in the Compiler directory have the «.bin» extension; these are versions of the interpreter which do not include the capability to load external script files. Instead, the program looks for a Win32 (RCDATA) resource named «>AUTOHOTKEY SCRIPT [v1.1.34+]: The standard AutoHotkey executable files can also be used as the base of a compiled script, by embedding a Win32 (RCDATA) resource with ID 1. (Additional scripts can be added with the AddResource compiler directive.) This allows the compiled script .exe to be used with the /script switch to execute scripts other than the main embedded script. For more details, see Embedded Scripts.

    Script Compiler Directives

    [v1.1.33+]: Script compiler directives allow the user to specify details of how a script is to be compiled. Some of the features are:

    • Ability to change the version information (such as the name, description, version. ).
    • Ability to add resources to the compiled script.
    • Ability to tweak several miscellaneous aspects of compilation.
    • Ability to remove code sections from the compiled script and vice versa.

    Compressing Compiled Scripts

    Ahk2Exe optionally uses MPRESS or [v1.1.33+] UPX freeware to compress compiled scripts. If MPRESS.exe and/or UPX.exe has been copied to the «Compiler» subfolder where AutoHotkey was installed, either can be used to compress the .exe as directed by the /compress parameter or the GUI setting.

    MPRESS official website (downloads and information): http://www.matcode.com/mpress.htm
    MPRESS mirror: https://www.autohotkey.com/mpress/

    UPX official website (downloads and information): https://upx.github.io/

    Note: While compressing the script executable prevents casual inspection of the script’s source code using a plain text editor like Notepad or a PE resource editor, it does not prevent the source code from being extracted by tools dedicated to that purpose.

    Background Information

    In [v1.1.33.10+] , the following folder structure is supported, where the running version of Ahk2Exe.exe is in the first Compiler directory shown below:

    The base file search algorithm runs for a short amount of time when Ahk2Exe starts, and works as follows:

    Qualifying AutoHotkey .exe files and all .bin files are searched for in the compiler’s directory, the compiler’s parent directory, and any of the compiler’s sibling directories with directory names that start with AutoHotkey or V , but do not start with AutoHotkey_H . The selected directories are searched recursively. Any AutoHotkey.exe files found are excluded, leaving files such as AutoHotkeyA32.exe, AutoHotkey64.exe, etc. plus all .bin files found. All .exe files that are included must have a name starting with AutoHotkey and a file description containing the word AutoHotkey , and must have a version of 1.1.34+ or 2.0-a135+ .

    A version of the AutoHotkey interpreter is also needed (as a utility) for a successful compile, and one is selected using a similar algorithm. In most cases the version of the interpreter used will match the version of the base file selected by the user for the compile.

    Passing Command Line Parameters to a Script

    Scripts support command line parameters. The format is:

    And for compiled scripts, the format is:

    Switches: Zero or more of the following:

    Send syntax errors that prevent a script from launching to the standard error stream (stderr) rather than displaying a dialog. See #ErrorStdOut for details. This can be combined with /iLib to validate the script without running it.

    [v1.1.33+]: An encoding can optionally be specified. For example, /ErrorStdOut=UTF-8 encodes messages as UTF-8 before writing them to stderr.

    [AHK_L 51+]: Overrides the default codepage used to read script files. For more details, see Script File Codepage.

    [v1.1.33+]: If «Default to UTF-8» is enabled in the installer, the «.ahk» file type is registered with a command line including /CP65001 . This causes all scripts launched through the shell (Explorer) to default to UTF-8 in the absence of a UTF-16 byte order mark. Scripts launched by running AutoHotkey.exe directly still default to CP0 , as the /CP65001 switch is absent.

    [v1.0.47+]: AutoHotkey loads the script but does not run it. For each script file which is auto-included via the library mechanism, two lines are written to the file specified by OutFile. These lines are written in the following format, where LibDir is the full path of the Lib folder and LibFile is the filename of the library:

    If the output file exists, it is overwritten. OutFile can be * to write the output to stdout.

    If the script contains syntax errors, the output file may be empty. The process exit code can be used to detect this condition; if there is a syntax error, the exit code is 2. The /ErrorStdOut switch can be used to suppress or capture the error message.

    [v1.1.34+]: Includes a file prior to the main script. Only a single file can be included by this method. When the script is reloaded, this switch is automatically passed to the new instance.

    [v1.1.34+]: When used with a compiled script based on an .exe file, this switch causes the program to ignore the main embedded script. This allows a compiled script .exe to execute external script files or embedded scripts other than the main one. Other switches not normally supported by compiled scripts can be used but must be listed to the right of this switch. For example:

    If the current executable file does not have an embedded script, this switch is permitted but has no effect.

    This switch is not supported by compiled scripts which are based on a .bin file.

    Script Filename: This can be omitted if there are no Script Parameters. If omitted (such as if you run AutoHotkey directly from the Start menu), the program looks for a script file called AutoHotkey.ahk in the following locations, in this order:

    • The directory which contains the AutoHotkey executable.
    • The current user’s Documents folder.

    The filename AutoHotkey.ahk depends on the name of the executable used to run the script. For example, if you rename AutoHotkey.exe to MyScript.exe, it will attempt to find MyScript.ahk . If you run AutoHotkeyU32.exe without parameters, it will look for AutoHotkeyU32.ahk.

    Note: In old versions prior to revision 51, the program looked for AutoHotkey.ini in the working directory or AutoHotkey.ahk in My Documents.

    [v1.1.17+]: Specify an asterisk (*) for the filename to read the script text from standard input (stdin). For an example, see ExecScript().

    [v1.1.34+]: If the current executable file has embedded scripts, this parameter can be an asterisk followed by the resource name or ID of an embedded script. For compiled scripts (i.e. if an embedded script with the ID #1 exists), this parameter must be preceded by the /script switch.

    Script Parameters: The string(s) you want to pass into the script, with each separated from the next by one or more spaces. Any parameter that contains spaces should be enclosed in quotation marks. If you want to pass an empty string as a parameter, specify two consecutive quotation marks. A literal quotation mark may be passed in by preceding it with a backslash (»). Consequently, any trailing slash in a quoted parameter (such as «C:My Documents » ) is treated as a literal quotation mark (that is, the script would receive the string C:My Documents » ). To remove such quotes, use StringReplace, 1, 1, » ,, All .

    [v1.1.27+]: Incoming parameters, if present, are stored as an array in the built-in variable A_Args, and can be accessed using array syntax. A_Args[1] contains the first parameter. The following example exits the script when too few parameters are passed to it:

    If the number of parameters passed into a script varies (perhaps due to the user dragging and dropping a set of files onto a script), the following example can be used to extract them one by one:

    If the parameters are file names, the following example can be used to convert them to their case-corrected long names (as stored in the file system), including complete/absolute path:

    Known limitation: dragging files onto a .ahk script may fail to work properly if 8-dot-3 (short) names have been turned off in an NTFS file system. One work-around is to compile the script then drag the files onto the resulting EXE.

    Legacy: The command line parameters are also stored in the variables %1%, %2%, and so on, as in versions prior to [v1.1.27] . In addition, %0% contains the number of parameters passed (0 if none). However, these variables cannot be referenced directly in an expression because they would be seen as numbers rather than variables. The following example exits the script when too few parameters are passed to it:

    If the number of parameters passed into a script varies (perhaps due to the user dragging and dropping a set of files onto a script), the following example can be used to extract them one by one:

    If the parameters are file names, the following example can be used to convert them to their case-corrected long names (as stored in the file system), including complete/absolute path:

    Script File Codepage [AHK_L 51+]

    In order for non-ASCII characters to be read correctly from file, the encoding used when the file was saved (typically by the text editor) must match what AutoHotkey uses when it reads the file. If it does not match, characters will be decoded incorrectly. AutoHotkey uses the following rules to decide which encoding to use:

    • If the file begins with a UTF-8 or UTF-16 (LE) byte order mark, the appropriate codepage is used and the /CPn switch is ignored.
    • If the /CPn switch is passed on the command-line, codepage n is used. For a list of possible values, see Code Page Identifiers.

    Note: The «Default to UTF-8» option in the AutoHotkey [v1.1.33+] installer adds /CP65001 to the command line for all scripts launched via the shell (Explorer).

  • In all other cases, the system default ANSI codepage is used.
  • Note that this applies only to script files loaded by AutoHotkey, not to file I/O within the script itself. FileEncoding controls the default encoding of files read or written by the script, while IniRead and IniWrite always deal in UTF-16 or ANSI.

    As all text is converted (where necessary) to the native string format, characters which are invalid or don’t exist in the native codepage are replaced with a placeholder: ANSI ‘?’ or Unicode ‘�’. In Unicode builds, this should only occur if there are encoding errors in the script file or the codepages used to save and load the file don’t match.

    RegWrite may be used to set the default for scripts launched from Explorer (e.g. by double-clicking a file):

    This assumes AutoHotkey has already been installed. Results may be less than ideal if it has not.

    Debugging a Script

    Commands such as ListVars and Pause can help you debug a script. For example, the following two lines, when temporarily inserted at carefully chosen positions, create «break points» in the script:

    When the script encounters these two lines, it will display the current contents of all variables for your inspection. When you’re ready to resume, un-pause the script via the File or Tray menu. The script will then continue until reaching the next «break point» (if any).

    It is generally best to insert these «break points» at positions where the active window does not matter to the script, such as immediately before a WinActivate command. This allows the script to properly resume operation when you un-pause it.

    The following commands are also useful for debugging: ListLines, KeyHistory, and OutputDebug.

    Some common errors, such as typos and missing «global» declarations, can be detected by enabling warnings.

    Interactive Debugging [AHK_L 11+]

    Interactive debugging is possible with a supported DBGp client. Typically the following actions are possible:

    • Set and remove breakpoints on lines — pause execution when a breakpoint is reached.
    • Step through code line by line — step into, over or out of functions and subroutines.
    • Inspect all variables or a specific variable.
    • View the stack of running subroutines and functions.

    Note that this functionality is disabled for compiled scripts which are based on a BIN file. For compiled scripts based on an EXE file, /debug must be specified after /script.

    To enable interactive debugging, first launch a supported debugger client then launch the script with the /Debug command-line switch.

    SERVER and PORT may be omitted. For example, the following are equivalent:

    [AHK_L 59+]: To attach the debugger to a script which is already running, send it a message as shown below:

    Once the debugger client is connected, it may detach without terminating the script by sending the «detach» DBGp command.

    Источник

    Adblock
    detector

    Switch Meaning Works compiled?
    /f or /force Launch unconditionally, skipping any warning dialogs. This has the same effect as #SingleInstance Off. Yes
    /r or /restart Indicate that the script is being restarted and should attempt to close a previous instance of the script (this is also used by the Reload command, internally). Yes
    /ErrorStdOut

    /ErrorStdOut=Encoding

    Yes
    /Debug [AHK_L 11+]: Connect to a debugging client. For more details, see Interactive Debugging. No
    /CPn

    Recommend Projects

    • React photo

      React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo

      Vue.js

      🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo

      Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo

      TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo

      Django

      The Web framework for perfectionists with deadlines.

    • Laravel photo

      Laravel

      A PHP framework for web artisans

    • D3 photo

      D3

      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Visualization

      Some thing interesting about visualization, use data art

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo

      Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo

      Microsoft

      Open source projects and samples from Microsoft.

    • Google photo

      Google

      Google ❤️ Open Source for everyone.

    • Alibaba photo

      Alibaba

      Alibaba Open Source for everyone

    • D3 photo

      D3

      Data-Driven Documents codes.

    • Tencent photo

      Tencent

      China tencent open source team.

    пытаясь запустить nohup python ~/file.py, после выполнения nohup.out показывает следующую ошибку….. и да, это автоподобный скрипт instagram, с которым я возился.

    File "/root/likebot.py", line 14
    hashtags = ['etsy', 'iOS', 'android', 'website'. 'webdesign', 'webdevelopment', 'graphic', 'smallbusiness', 'business', 'design', 'ineedawebsite', 'oregon', 'washington', 'idaho', 'oklahoma', 'life', 'usa', 'entrepreneur', 'responsive']
                                                               ^SyntaxError: invalid syntax
    

    Что здесь недействительно?

    В качестве примечания, если вы шутки в сторону подозреваете, что что-то изменилось в Python со времени вашей последней использовавшейся версии, из-за чего ранее действующий код больше не действует, вам действительно нужно сообщить нам, какую версию вы используете сейчас и какую версию вы использовали раньше. (Большинство кардинальных изменений произошло между 2.x и 3.x, но есть код, который был действительным кодом 2.5, а также ошибка в 2.6 и т. д.) — abarnert

    @dp.message_handler(content_types=[‘photo’], state= FSMAdmin.photo)ы
    async def load_photo(message: types.Message, state: FSMContext):
    async while state.proxy() as data:
    data[‘photo’] = messaege.photo[0].file_id
    await FSMAdmin.next()
    await message.reply(«Теперь введите название»)

    Ощибка
    Traceback (most recent call last):
    File «C:Новая папкаlibrunpy.py», line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
    File «C:Новая папкаlibrunpy.py», line 86, in _run_code
    exec(code, run_globals)
    File «c:Userspmkut.vscodeextensionsms-python.python-2022.20.2pythonFileslibpythondebugpy__main__.py», line 39, in
    cli.main()
    File «c:Userspmkut.vscodeextensionsms-python.python-2022.20.2pythonFileslibpythondebugpy/..debugpyservercli.py», line 430, in main
    run()
    File «c:Userspmkut.vscodeextensionsms-python.python-2022.20.2pythonFileslibpythondebugpy/..debugpyservercli.py», line 284, in run_file
    runpy.run_path(target, run_name=»__main__»)
    File «c:Userspmkut.vscodeextensionsms-python.python-2022.20.2pythonFileslibpythondebugpy_vendoredpydevd_pydevd_bundlepydevd_runpy.py», line 320, in run_path
    code, fname = _get_code_from_file(run_name, path_name)
    File «c:Userspmkut.vscodeextensionsms-python.python-2022.20.2pythonFileslibpythondebugpy_vendoredpydevd_pydevd_bundlepydevd_runpy.py», line 294, in _get_code_from_file
    code = compile(f.read(), fname, ‘exec’)
    File «c:BTpizza_at_homeHANDLERSadmin.py», line 24
    async while state.proxy() as data:
    ^^^^^
    SyntaxError: invalid syntax

    Не могу понять в чем ошибка

    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии

    А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка аутентификации пользователя фгис фри
  • Ошибка ахк error line 1