初学者AppleScript Writer闲置处理程序遇到问题 [英] Beginner AppleScript Writer having trouble with idle handler

查看:79
本文介绍了初学者AppleScript Writer闲置处理程序遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在探索编码,我非常喜欢将问题细化.我现在对AppleScript感到满意,并且我认为这是将来我要使用编码进行操作的一个不错的选择.我的直觉告诉我,Automator会降低RAM的效率,而且我不喜欢它的分割方式.限制和混乱.我喜欢脚本语言的沙箱功能.我为网络爬虫构建了一个非常不错的脚本,该脚本打开了在线股票投资组合并修剪了加密货币的市场价格.我计划利用技术决策实验室来创建一个加密货币预测工作簿,以实现我的希望和梦想,即使有一天也要赚钱:[我的梦想是制作一个实时excel文件,该文件可以构建具有每小时波动的图表.

I have been exploring coding recently and I really enjoy grinding a problem down. I am getting comfortable with AppleScript now and I think it is a good option for what I want to do in the future with coding. My gut tells me that Automator would be less efficient RAM wise and I don't like how it is sectioned off; to constraining and confusing. I like the sandbox feature of a scripting language. I built a pretty good script for a web crawler that opens an online stock portfolio and prunes the market price of cryptocurrencies. I plan on utilizing technological decision making labs to create a cryptocurrency forecasting workbook for my hopes and dreams to make money some day, if ever :[ I have day dreams of making a live excel file that builds plots with hourly fluctuations in the trading.

要使其成为一个完整的自动化系统,我需要某种方式来循环脚本或安排其按计划运行,以获取我希望从数据中得出的数学模型的大量数据点.我已经尽力真的使空闲处理程序正常工作,但是它不能像教程中描述的那样运行.看来您无法使用闲置"状态使用某些命令,每次使用该东西时,我都会遇到错误.我找到了一个帮助页面,该页面显示了如何结合哔哔声".功能以确保空闲循环正在运行,并且在我编译并另存为始终运行的应用"时它不会发出提示音,所以我想这是我还没有弄清楚的另一个问题.有时我会发出哔哔声,但是现在程序的最终草案使我无法正常工作.我曾经尝试过非常仔细地将其插入tell语句中,因为我发现它有时可以与他们一起使用.而且我想您不能让空闲的处理程序跨越整个脚本.它需要在一个命令结构树中被调用才能起作用.但是我仍然没有让应用程序从空闲状态开始运行脚本,而我已经在研究该解决方案中进行了所有工作.任何对空闲处理程序机密都保持安静的人都可以尽力向我解释脚本的内部工作原理,但是我发现学习编码需要花费很长时间,因为这涉及很多非常技术性的阅读.难得的机会,可以进行自己的学习.编码是很多重复的工作,我想我将用到目前为止所学的知识,花很多时间写代码到我的白发时代.

To make it a full fledged automated system I need some sort of way to loop the script or schedule it to run on a schedule to get lots of data points for the mathematical models I hope to formulate from the data. I have tried really hard to make the idle handler work but it just doesn't operate like the tutorials describe. It seems you can't use "on idle" with certain commands and I get an error every gosh darn time I use the thing. I found a help page that showed how to incorporate a "beep" function to make sure the idle loop is running and when I compile and save as an "always running App" it doesn't play the beep so I guess that's another problem I haven't figured out. I get the beep to work sometimes but with my final draft of my program now I can't get it to work. I have tried inserting it ever so carefully within tell statements because I have found it works with them sometimes. And I guess you can't have the idle handler span the entire script; it needs to be called in one command structures tree to work. But I still haven't had the App run the script from idle with all the work I've put in looking into this solution. Anybody that has the hush hush on the idle handler secrets can do their best to try to explain the inner workings of the script to me but I find that it takes me a long time to learn coding because it is a lot of very technical reading with precious few opportunities to forge your own learning. Coding is a lot of boiler plate rehashes and I assume I will be chipping away at writing code long into my grey hair days with what I've learned so far.

但是,如果您可以使用此问题来收集一些阅读材料,以了解如何采用适当编写的脚本以能够很好地处理大多数计算负载的笔记本电脑为背景,以30分钟为增量运行,那么将不胜感激.我不反对Automator;要使它正常工作,您必须了解所有事情,这本身就是一件困难的事情.正如我所说,有关空闲处理程序以及如何使其工作的任何信息都将有所帮助.另外,如果可以在AppleScript中编写代码以在Microsoft Excel中生成图,我喜欢为衬衫和Google制作模型.

But if you could use this question to collect some reading material on how to take a moderately well written script to run in 30 minute increments in the background of a laptop that can handle most computing loads fairly well it would be most appreciated. I'm not against Automator; it's just hard in it's own right with all the things you have to know to get it to work. As I said, any info about the idle handler and how to get it to work would be helpful. Also, if it is possible to write code in AppleScript to generate plots in Microsoft Excel, I like making models for shirts and googles.

我想我将分享我在过去一周免费学习当前在线提供的教程中最后一部分工作的成果.对于如何使我到目前为止变得更好的脚本提出的任何批评或建议都将受到赞赏,如果我做的很好,我不介意您抢走喜欢的东西.这是当前的网络爬网加密货币股票分析器.它遵循3种货币,并用年,月,日和秒将数据写入excel文件,以收集大量数据以建立更强大的数学模型.我研究了将季节性应用于数据的技术预测技术,因此与使用excel中的趋势线函数进行预测相比,预测要好得多,尽管随着加密货币的可变性,我不会对市场价格的长期预测投入太多精力.我只想留意这些事情,以至于如此令人发指的股票崩盘,让我有机会用我可以勉强维持的很少的钱来the足游戏.

I guess I will share what I've worked on for the last chunk of a weeks worth of grinding the tutorials offered currently online for free. Any critiques or suggestions on how to make the script I've got so far better is greatly appreciated and I don't mind if you snatch something you like if I did a good jerb. This is a web crawling cryptocurrency stock analyzer currently. It follows 3 currencies and writes data to an excel file with year, month, day, and seconds to collect a mass of data for a stronger mathematical model. I studied technological forecasting techniques that apply seasonality to data so the forecasts are better than just using the trend line function in excel, though with the variability with cryptocurrency I wouldn't put much salt on a long term prediction of market prices. I just want to be watching for those oh so gut wrenching stock crashes for a chance to limp in to the game with what little money I can scrounge together for sustenance.

--Boiler plate code to manipulate the HTML to let us pull the market price of the stock.--
--3 sets of modifiers for the 3 stocks--
to extractTextBitcoin(searchTextBitcoin, startTextBitcoin, endTextBitcoin)
    set tid to AppleScript's text item delimiters
    set startTextBitcoin to ">"
    set searchTextBitcoin to {"priceValue___11gHJ", 0 & searchTextBitcoin}
    set AppleScript's text item delimiters to startTextBitcoin
    set endItemsBitcoin to text item -1 of searchTextBitcoin
    set AppleScript's text item delimiters to endTextBitcoin
    set beginningToEndBitcoin to text item 1 of endItemsBitcoin
    set AppleScript's text item delimiters to startTextBitcoin
    set endTextBitcoin to (text items 2 thru -1 of beginningToEndBitcoin) as record
    set AppleScript's text item delimiters to tid
end extractTextBitcoin

to extractTextLitecoin(searchTextLitecoin, startTextLitecoin, endTextLitecoin)
    set tid to AppleScript's text item delimiters
    set startTextLitecoin to ">"
    set searchTextLitecoin to {"priceValue___11gHJ", 0 & searchTextLitecoin}
    set AppleScript's text item delimiters to startTextLitecoin
    set endItemsLitecoin to text item -1 of searchTextLitecoin
    set AppleScript's text item delimiters to endTextLitecoin
    set beginningToEndLitecoin to text item 1 of endItemsLitecoin
    set AppleScript's text item delimiters to startTextLitecoin
    set endTextLitecoin to (text items 2 thru -1 of beginningToEndLitecoin) as record
    set AppleScript's text item delimiters to tid
end extractTextLitecoin

to extractTextDogecoin(searchTextDogecoin, startTextDogecoin, endTextDogeecoin)
    set tid to AppleScript's text item delimiters
    set startTextDogecoin to ">"
    set searchTextDogecoin to {"priceValue___11gHJ", 0 & searchTextDogecoin}
    set AppleScript's text item delimiters to startTextDogecoin
    set endItemsDogecoin to text item -2 of searchTextDogecoin
    set AppleScript's text item delimiters to endTextDogeecoin
    set beginningToEndDogecoin to text item 1 of endItemsDogecoin
    set AppleScript's text item delimiters to startTextDogecoin
    set endTextDogeecoin to (text items 2 thru -1 of beginningToEndDogecoin) as record
    set AppleScript's text item delimiters to tid
end extractTextDogecoin

--A tell statement to open the webpage where the stocks are measured--
tell application "Safari"
    activate
    do shell script "open https://coinmarketcap.com/currencies/bitcoin/"
end tell

delay 2

--A function that differentiates the data on the web page by class and number. It
--also uses JavaScript to write the data to a useable format.
to getInputByClassBitcoin(theClass, num)
    tell application "Safari"
        set input to do JavaScript "
        document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
    end tell
    return input
end getInputByClassBitcoin

--The function with the class and number criteria manually pulled from the web page--
getInputByClassBitcoin("priceValue___11gHJ", 0)

--Setting the instataneous stock price to a variable to input in Excel--
set BitcoinPrice to getInputByClassBitcoin("priceValue___11gHJ", 0)
on FinalFuction(BitcoinPrice)
    set FinalFuction to extractTextBitcoin(BitcoinPrice, "<div class=>", "</div>")
    return FinalFuction(BitcoinPrice)
end FinalFuction

tell application "Safari"
    activate
    do shell script "open https://coinmarketcap.com/currencies/litecoin/"
end tell

delay 2

to getInputByClassLitecoin(theClass, num)
    tell application "Safari"
        set token to do JavaScript "
        document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
    end tell
    return token
end getInputByClassLitecoin

getInputByClassLitecoin("priceValue___11gHJ", 0)

set LitecoinPrice to getInputByClassLitecoin("priceValue___11gHJ", 0)
on ReturnFuction(LitecoinPrice)
    set ReturnFuction to extractTextLitecoin(LitecoinPrice, "<div class=>", "</div>")
    return ReturnFuction(LitecoinPrice)
end ReturnFuction

tell application "Safari"
    activate
    do shell script "open https://coinmarketcap.com/currencies/dogecoin/"
end tell

delay 2

to getInputByClassDogecoin(theClass, num)
    tell application "Safari"
        set blast to do JavaScript "
        document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
    end tell
    return blast
end getInputByClassDogecoin

getInputByClassDogecoin("priceValue___11gHJ", 0)

set DogecoinPrice to getInputByClassDogecoin("priceValue___11gHJ", 0)
on EndFuction(DogecoinPrice)
    set EndFuction to extractTextDogecoin(DogecoinPrice, "<div class=>", "</div>")
    return EndFuction(DogecoinPrice)
end EndFuction

--Opens the compiled Excel workbook, negates user input, finds the next available--
--cell to input data, and fills the fields with Year, Month, Day, Time, and Price--
tell application "Microsoft Excel"
    open "/Users/clusterflux/Desktop/ㅇㅅㅇBITCOINㅇㅅㅇ.xlsx"
    set display alerts to false
    delete active sheet
    first row index of (get end (last cell of column 9) direction toward the top)
    set LastRow to first row index of (get end (last cell of column 9) direction toward the top)
    --write date and time for each market reading to excel file
    set value of cell ("I" & LastRow + 1) to "=YEAR(TODAY())"
    set value of cell ("J" & LastRow + 1) to "=MONTH(TODAY())"
    set value of cell ("K" & LastRow + 1) to "=DAY(TODAY())"
    set value of cell ("L" & LastRow + 1) to (time string of (current date))
    set value of cell ("M" & LastRow + 1) to BitcoinPrice
    set workbookName to ("ㅇㅅㅇBITCOINㅇㅅㅇ.xlsx") as string
    set destinationPath to (path to desktop as text) & workbookName
    save active workbook in destinationPath
end tell

tell application "Microsoft Excel"
    open "/Users/clusterflux/Desktop/ㅇㅅㅇLITECOINㅇㅅㅇ.xlsx"
    set display alerts to false
    delete active sheet
    first row index of (get end (last cell of column 5) direction toward the top)
    set LastRow to first row index of (get end (last cell of column 5) direction toward the top)
    set value of cell ("C" & LastRow + 1) to "=YEAR(TODAY())"
    set value of cell ("D" & LastRow + 1) to "=MONTH(TODAY())"
    set value of cell ("E" & LastRow + 1) to "=DAY(TODAY())"
    set value of cell ("F" & LastRow + 1) to (time string of (current date))
    set value of cell ("G" & LastRow + 1) to LitecoinPrice
    set workbookName to ("ㅇㅅㅇLITECOINㅇㅅㅇ.xlsx") as string
    set destinationPath to (path to desktop as text) & workbookName
    save active workbook in destinationPath
end tell
on idle
    return 3
    beep
    tell application "Microsoft Excel"
        open "/Users/clusterflux/Desktop/ㅇㅅㅇDOGECOINㅇㅅㅇ.xlsx"
        set display alerts to false
        delete active sheet
        first row index of (get end (last cell of column 5) direction toward the top)
        set LastRow to first row index of (get end (last cell of column 5) direction toward the top)
        set value of cell ("C" & LastRow + 1) to "=YEAR(TODAY())"
        set value of cell ("D" & LastRow + 1) to "=MONTH(TODAY())"
        set value of cell ("E" & LastRow + 1) to "=DAY(TODAY())"
        set value of cell ("F" & LastRow + 1) to (time string of (current date))
        set value of cell ("G" & LastRow + 1) to DogecoinPrice
        set workbookName to ("ㅇㅅㅇDOGECOINㅇㅅㅇ.xlsx") as string
set destinationPath to (path to desktop as text) & workbookName
        save active workbook in destinationPath
    end tell
end idle

对不起,如果我的格式还不够完善.我仍然是新手.

Sorry in advance if my formatting isn't up to snuff. I'm still a newbie.

推荐答案

这里是另一种AppleScript方法,使您无需打开Safari,使用JavaScript,Automator或使用文本项定界符即可检索比特币价格值.这可能并不是您想要的,但至少它使用更少的代码提供了一种不同的方法.希望您可以适应其中的一些需求.

Here is a different AppleScript approach which allows you to retrieve your Bitcoin Price values without the need for opening Safari, using JavaScript, Automator, or using text item delimiters. This may not be exactly what you’re looking for but at least it offers a different approach using much less code. Hopefully you can adapt some of it to your needs.

代码中的前3个属性定义正则表达式,将在 do shell script 命令中使用该命令,这些命令将从HTML源代码中提取美元价值

The first 3 properties in the code define the regular expressions which will be used in the do shell script commands, which will extract the dollar values from the HTML source code.

例如,为了快速解释什么属性eGrepBitcoinPrice:"priceValue ___ 11gHJ \"> \\ $ \\ d {2},\\ d {3}.\\ d {2}" 意思是……我们将在HTML内搜索包含"priceValue___11gHJ"后跟>"的文本后面跟着"$",后跟任意两位数字,后跟,",然后跟着任意3位数字,再跟一个."并后跟任意两位数字

For example, to quickly explain what property eGrepBitcoinPrice : "priceValue___11gHJ\">\\$\\d{2},\\d{3}.\\d{2}" means… we will be searching for text inside the HTML which contains "priceValue___11gHJ" followed by a ">" followed by "$" followed by any 2 digits followed by a "," followed by any 3 digits followed by a "." and followed by any 2 digits

由于我没有Microsoft Excel,因此无法在代码中包含这些命令.但是,我确实创建了一个快速日志记录功能,可以将价格写到桌面"Price Log.txt"上的纯文本文件中.此功能可以轻松禁用或删除.日志命令全部包裹在名为 script logCommands script对象中,可以将其与包含我的logCommands的代码中的其他任何行一起删除或注释掉..

Because I do not have Microsoft Excel, I could not include those commands in the code. However, I did create a quick logging function which writes the prices to a plain text file on your Desktop "Price Log.txt". This functionality can easily be disabled or removed. The log commands are all wrapped up within a script object called script logCommands which can be removed or commented out along with any other lines in the code which contain my logCommands's.

这是日志文件的快照

将下面的AppleScript代码保存在Script Editor.app中,作为保持打开"应用程序.由于它是一个保持开放"的应用程序,因此在Script Editor.app之外启动小程序时,只有显式 on 处理程序中的内容仅运行一次.其余的魔法发生在 online 处理程序中……并且此处理程序中的所有内容每300秒运行一次.如果希望命令每30分钟重复一次,只需将 return 值设置为1800.

Save this following AppleScript code in Script Editor.app as a "stay open" application. Being that it is a "stay open" application, when the applet is launched outside of Script Editor.app, only what is within the explicit on run handler will run only one time. The rest of the magic happens within the on idle handler… and everything within this handler will run every 300 seconds. If you want the commands to repeat every 30 minutes, just set the return value to 1800.

property eGrepBitcoinPrice : "priceValue___11gHJ\">\\$\\d{2},\\d{3}.\\d{2}"
property eGrepLitecoinPrice : "priceValue___11gHJ\">\\$\\d{3}.\\d{2}"
property eGrepDogecoinPrice : "priceValue___11gHJ\">\\$\\d{1}.\\d{5}"
property currentBitcoinPrice : missing value
property currentLitecoinPrice : missing value
property currentDogecoinPrice : missing value
property logToTextFile : missing value

on run --   Executed Only Once.. When This Script Applet Is Launched
    activate
    set logToTextFile to (display dialog ¬
        "Enable Quick Log Mode?" buttons {"No", "Yes"} ¬
        default button 2 with title "Log Mode")
    if button returned of logToTextFile = "Yes" then
        my logCommands's beginLog()
        getPrices()
    else
        getPrices()
        return {currentBitcoinPrice, currentDogecoinPrice, currentLitecoinPrice}
    end if
end run

on idle
    getPrices()
    if button returned of logToTextFile = "Yes" then my logCommands's writeToLog()
    
    (* within this idle handler is where you will place
    The bulk of your additional code. All of your Excel
    Code Goes Here*)
    
    return 300 -- In Seconds, How Often To Run Code In This Idle Handler
end idle

---------- PLACE ALL HANDLERS BENEATH THIS LINE ----------

on getPrices()
    set currentBitcoinPrice to do shell script ¬
        "curl --no-keepalive 'https://coinmarketcap.com/currencies/bitcoin/markets/' " & ¬
        "| grep -Eo " & quoted form of eGrepBitcoinPrice & " | cut -c 21-"
    set currentLitecoinPrice to do shell script ¬
        "curl --no-keepalive 'https://coinmarketcap.com/currencies/litecoin/' " & ¬
        "| grep -Eo " & quoted form of eGrepLitecoinPrice & " | cut -c 21-"
    set currentDogecoinPrice to do shell script ¬
        "curl --no-keepalive 'https://coinmarketcap.com/currencies/dogecoin/' " & ¬
        "| grep -Eo " & quoted form of eGrepDogecoinPrice & " | cut -c 21-"
end getPrices

on quit --  Executed Only When The Script Quits
    if button returned of logToTextFile = "Yes" then my logCommands's endLog()
    continue quit -- Allows The Script To Quit
end quit

script logCommands
    property pathToPriceLog : POSIX path of (path to desktop as text) & "Price Log.txt"
    on beginLog()
        set startTime to ("Start Time... " & (current date) as text) & ¬
            " Price Scanning At 5 Minute Intervals"
        do shell script "echo " & startTime & " >> " & ¬
            quoted form of pathToPriceLog
    end beginLog
    on writeToLog()
        do shell script "echo " & "Bitcoin:" & quoted form of currentBitcoinPrice & ¬
            "   Dogecoin:" & quoted form of currentDogecoinPrice & ¬
            "  Litecoin:" & quoted form of currentLitecoinPrice & ¬
            "     " & quoted form of (time string of (current date)) & ¬
            " >> " & quoted form of pathToPriceLog
    end writeToLog
    on endLog()
        set endTime to quoted form of "End Time... " & (current date) as text
        do shell script "echo " & endTime & " >> " & ¬
            quoted form of pathToPriceLog
        do shell script "echo " & " " & " >> " & ¬
            quoted form of pathToPriceLog
    end endLog
end script

不幸的是,从Script Editor.app中启动时保持打开状态"的应用程序和脚本将不会执行 idle handler 中的内容.因此,需要像其他任何应用程序一样,从Finder中启动保持打开状态"应用程序,以观察 idle 命令的执行结果.这是我包括记录文件功能的主要原因……因此我可以实时观察 idle 命令的结果.

Unfortunately "stay open" applications and scripts when launched from within Script Editor.app, will not execute what is within the idle handler. So the "stay open" application needs to be launched from within Finder, like any other applications, to observe the results of the idle commands as they are happening. This was the main reason I included a logging to file function… so I could observe the results of the idle commands in real time.

与许多人的看法相反,大多数保持开放"的应用程序只使用很少的系统资源.

Contrary to what a lot of people think, most "stay open" applications use very little system resources.

这篇关于初学者AppleScript Writer闲置处理程序遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆