Selection from the end of a track to the nearest second

I want to be able to take any given audio track and automatically create a selection from the end of the track to the nearest whole second. For example, if I have a track that ends at 3.6 seconds, I would want a selection from 3.6 - 4.0 seconds, without any user input required. Is this possible to do with a Python script in Audacity?

This script is written for Linux. It’ll need a bit of modification for Windows (see: https://github.com/audacity/audacity/blob/master/scripts/piped-work/pipe_test.py)

#!/usr/bin/env python
# -*- coding: utf-8 -*

import os
import json

TONAME = '/tmp/audacity_script_pipe.to.' + str(os.getuid())
FROMNAME = '/tmp/audacity_script_pipe.from.' + str(os.getuid())
TOFILE = open(TONAME, 'w')
FROMFILE = open(FROMNAME, 'rt')

def send_command(command):
  TOFILE.write(command + "\n")
  TOFILE.flush()


def get_response():
    """Return the command response."""
    result = ''
    line = ''
    while True:
        result += line
        line = FROMFILE.readline()
        if line == '\n' and len(result) > 0:
            break
    return result


def do_command(command):
  """Send one command, and return the response."""
  send_command(command)
  response = get_response()
  return response


command = "GetInfo: Type=Tracks"
info = (do_command(command))

#Trim info to JSON data
info = info[1:-26]

track_data = json.loads(info)
first_track_end = track_data[0]["end"]

start = int(first_track_end)
end = start + 1

# Send command
command = 'SelectAll:'
(do_command(command))

command = f'SelectTime: Start={start}  End={end}'
(do_command(command))

Not what you asked for, but it’s a lot simpler with a “Nyquist Macro” https://manual.audacityteam.org/man/nyquist_macros.html

Select part, or all of the track, then run this in the Nyquist Prompt (https://manual.audacityteam.org/man/nyquist_prompt.html)
It’ll be quite slow the first time that you run it, but faster after the first run.

;type tool

(setf end (second  (assoc 'end (first (aud-get-info "Tracks")))))
(setf start (truncate end))
(setf end (1+ start))
(aud-do-command "SelectTime" :start start :end end)
""

An alternative Python script using pipeclient (See: https://github.com/audacity/audacity/blob/master/scripts/piped-work/pipeclient.py)

#!/usr/bin/env python
# -*- coding: utf-8 -*

import json
import time
import pipeclient

client = pipeclient.PipeClient()

client.write('GetInfo: Type=Tracks')
# Wait for reply
info = ""
while info == "":
  info = client.read()
  time.sleep(0.05)

#Trim info to JSON data
info = info[:-26]
#print('Info: ', info)

track_data = json.loads(info)
first_track_end = track_data[0]["end"]

start = int(first_track_end)
end = start + 1

client.write('SelectAll:')
client.write(f'SelectTime: Start={start}  End={end}')