【问题标题】:Issue with AHK file readingAHK 文件读取问题
【发布时间】:2020-06-29 12:07:55
【问题描述】:

我正在编写一个简单的 AHK 程序,它从 .txt 中获取文本并输出它们。 当它运行时,它会反复发送存储在line 中的任何占位符值。

SetWorkingDir %A_ScriptDir%
timer := 1050
line = 0
^q::
    Loop, Read, %A_WorkingDir%\read.txt { 
        line := %A_LoopReadLine%
        Settimer, Label, %timer%
Return
^+q::ExitApp
Label:
    Send %line%{enter}
Return

输出:

0
0
0
...

代码目录中的唯一文件是它本身和 read.txt。 我怀疑这是我滥用目录语法。

【问题讨论】:

    标签: autohotkey


    【解决方案1】:

    我看到了四个实际问题。
    { 在错误的行上,缺少结束 },在表达式语句中使用旧语法,并且使用错误的计时器。

    首先,您不能将起始 { 与文件名放在同一行(以 OTB 用户为例)。它将被视为文件名的一部分。
    将大括号放下一行。

    然后缺少右大括号,应该很明显。应该添加(假设我们首先修复代码中的其他问题)

    然后在表达式语句中使用旧语法。
    line := %A_LoopReadLine%
    通过将变量包装在 %% 中来引用变量是您在古老且已弃用的遗留 AHK 语法中所做的事情。但是您正在使用 := 将表达式分配给变量。与将文字文本分配给变量相反,这是旧版 = 所做的(= 不应再用于分配值,并且可以说%% 也不应使用)。
    因此,在现代表达式语句中,您只需键入变量名称即可引用该变量。放弃%s。

    然后是计时器。我只能猜测你为什么在那里有一个计时器。我假设您可能认为它的作用与实际作用不同。
    timer 的基本作用是每 x 毫秒启动一个预定义的函数/标签。
    你试图做的是启动一堆计时器,无论你的循环发生在什么线上,它们都会随机喷出。 (循环将在单个计时器有时间做任何事情之前结束)

    修改后的代码:

    ;this is already the working directory by
    ;default, this does nothing for us
    ;SetWorkingDir %A_ScriptDir%
    
    ;neither of these does anything for us
    ;removed
    ;timer := 1050
    ;line = 0
    
    ^q::
        ;the file is assumned to be in the working directory
        ;by default, no need to explicitly specify it
        ;
        ;also forced expression syntax for the parameter
        ;by starting it off with a % and a space to
        ;explicitly specify we're working with a string
        ;not actually needed, but looks better if you
        ;ask me
        Loop, Read, % "read.txt"
        {
            ;ditched the legacy syntax and switched
            ;over to SendInput, it's documented as
            ;faster and more reliable
            line := A_LoopReadLine
            SendInput, % line "{Enter}"
        }
    Return
    
    ^+q::ExitApp
    

    我的回答可能让您对遗留语法和表达式语法感到困惑,here's 我之前关于%%% 的回答。
    还包括 documentation link 以了解更多关于旧版与表达式的信息。


    作为奖励,如果您有兴趣了解您的脚本究竟做了什么,以下是发生的事情:
    循环试图读取一个名为%A_WorkingDir%\read.txt {的文件。
    不存在这样的文件,因此循环甚至没有启动。
    然后它进入计时器,开始每 1050 毫秒打印一次 0(这是您分配给 line 变量的值)。
    这将永远持续下去。

    【讨论】:

    • 谢谢,我用 Sleep, 1050 替换了计时器,它起作用了!
    猜你喜欢
    • 1970-01-01
    • 2017-11-30
    • 2014-07-14
    • 2012-05-09
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多