open(3tcl)

✨ NAME ✨

open β€” open a file-based or command pipeline channel

okay so hi bestie πŸ’– this is the page for open(3tcl), from the Tcl Built-In Commands manual. It's a long one, so buckle up, hydrate, and let's go 🫢


🌸 SYNOPSIS 🌸

open fileName
open fileName access
open fileName access permissions

πŸ’… DESCRIPTION πŸ’…

This command opens a file, a serial port, or a command pipeline, and hands you back a channel identifier that you can use in future invocations of commands like read, puts, and close. Iconic behaviour, honestly. ✨

If the first character of fileName is not |, then the command opens a file: fileName gives the name of the file to open, and it has to conform to the conventions described in the filename manual entry. No cap.

The access argument, if you bother to pass it, tells Tcl how the file (or command pipeline) is meant to be accessed. In the first form, access can be any of these:

  • r β€” open the file for reading only; the file must already exist. This is the default value if access isn't specified. πŸŽ€
  • r+ β€” open the file for both reading and writing; the file must already exist.
  • w β€” open the file for writing only. Truncate it if it exists. If it doesn't exist, create a new file. (yes it will absolutely eat your existing content, be normal about it 😭)
  • w+ β€” open the file for reading and writing. Truncate it if it exists. If it doesn't exist, create a new file.
  • a β€” open the file for writing only. If the file doesn't exist, create a new empty file. Set the file pointer to the end of the file prior to each write. ✍️
  • a+ β€” open the file for reading and writing. If the file doesn't exist, create a new empty file. Set the initial access position to the end of the file.

All of the legal access values above can have the character b added as the second or third character in the value, which signals that the opened channel should be configured as if with the fconfigure -translation binary option β€” making the channel suitable for reading or writing of binary data. 🧚

In the second form, access is a list of any of the following flags, most of which have the standard POSIX meanings. One of the flags must be either RDONLY, WRONLY or RDWR. periodt.

  • RDONLY β€” open the file for reading only.
  • WRONLY β€” open the file for writing only.
  • RDWR β€” open the file for both reading and writing.
  • APPEND β€” set the file pointer to the end of the file prior to each write.
  • BINARY β€” configure the opened channel with the -translation binary option.
  • CREAT β€” create the file if it doesn't already exist (without this flag it is an error for the file not to exist).
  • EXCL β€” if CREAT is also specified, an error is returned if the file already exists. 🚫
  • NOCTTY β€” if the file is a terminal device, this flag prevents the file from becoming the controlling terminal of the process.
  • NONBLOCK β€” prevents the process from blocking while opening the file, and possibly in subsequent I/O operations. The exact behavior of this flag is system- and device-dependent; its use is discouraged (it's better to use the fconfigure command to put a file in nonblocking mode). For details, refer to your system documentation on the open system call's O_NONBLOCK flag. πŸ™ˆ
lowkey a trap, bestie β€” the docs literally say discouraged. use fconfigure instead, iykyk.
  • TRUNC β€” if the file exists it is truncated to zero length.

If a new file is created as part of opening it, permissions (an integer) is used to set the permissions for the new file in conjunction with the process's file mode creation mask. permissions defaults to 0666. πŸ‘‘

When the file opened is an ordinary disk file, the chan configure and fconfigure commands can be used to query this additional configuration option:

  • -stat β€” this option, when read, returns a dictionary of values much as is obtained from the file stat command, where that stat information relates to the real opened file. Keys in the dictionary may include atime, ctime, dev, gid, ino, mode, mtime, nlink, size, type, and uid among others; the mtime, size and type fields are guaranteed to be present and meaningful on all platforms; other keys may be present too. 🌈

Implementation note: this option maps to a call to fstat() on POSIX platforms, and to a call to GetFileInformationByHandle() on Windows; the information reported is what those system calls produce.


πŸ”₯ COMMAND PIPELINES πŸ”₯

If the first character of fileName is | then the remaining characters of fileName are treated as a list of arguments that describe a command pipeline to invoke, in the same style as the arguments for exec. Main character energy, truly. ✨

In this case, the channel identifier returned by open may be used to write to the command's input pipe or read from its output pipe, depending on the value of access.

  • If write-only access is used (e.g. access is w), then standard output for the pipeline is directed to the current standard output unless overridden by the command.
  • If read-only access is used (e.g. access is r), standard input for the pipeline is taken from the current standard input unless overridden by the command.

The id of the spawned process is accessible through the pid command, using the channel id returned by open as argument. 🫢

If the command (or one of the commands) executed in the command pipeline returns an error (according to the definition in exec), a Tcl error is generated when close is called on the channel β€” unless the pipeline is in non-blocking mode, then no exit status is returned (a silent close with -blocking 0). πŸ’€

It is often useful to use the fileevent command with pipelines so other processing may happen at the same time as running the command in the background. multitasking queen behaviour πŸ’…


πŸ¦‹ SERIAL COMMUNICATIONS πŸ¦‹

If fileName refers to a serial port, then the specified serial port is opened and initialized in a platform-dependent manner. Acceptable values for the fileName to use to open a serial port are described in the PORTABILITY ISSUES section.

The chan configure and fconfigure commands can be used to query and set additional configuration options specific to serial ports (where supported):

  • -mode baud,parity,data,stop β€” this option is a set of 4 comma-separated values: the baud rate, parity, number of data bits, and number of stop bits for this serial port. The baud rate is a simple integer that specifies the connection speed. Parity is one of the following letters: n, o, e, m, s; respectively signifying the parity options of "none", "odd", "even", "mark", or "space". Data is the number of data bits and should be an integer from 5 to 8, while stop is the number of stop bits and should be the integer 1 or 2. πŸŽ€
  • -handshake type β€” (Windows and Unix). This option is used to setup automatic handshake control. Note that not all handshake types maybe supported by your operating system. The type parameter is case-independent.

If type is none then any handshake is switched off. rtscts activates hardware handshake. Hardware handshake signals are described below. For software handshake xonxoff the handshake characters can be redefined with -xchar. An additional hardware handshake dtrdsr is available only under Windows. There is no default handshake configuration, the initial value depends on your operating system settings. The -handshake option cannot be queried.

  • -queue β€” (Windows and Unix). The -queue option can only be queried. It returns a list of two integers representing the current number of bytes in the input and output queue respectively. πŸ‘€
  • -timeout msec β€” (Windows and Unix). This option is used to set the timeout for blocking read operations. It specifies the maximum interval between the reception of two bytes in milliseconds. For Unix systems the granularity is 100 milliseconds. The -timeout option does not affect write operations or nonblocking reads. This option cannot be queried.
  • -ttycontrol {signal boolean signal boolean ...} β€” (Windows and Unix). This option is used to setup the handshake output lines (see below) permanently or to send a BREAK over the serial line. The signal names are case-independent. {RTS 1 DTR 0} sets the RTS output to high and the DTR output to low. The BREAK condition (see below) is enabled and disabled with {BREAK 1} and {BREAK 0} respectively.
it is not a good idea to change the RTS (or DTR) signal with active hardware handshake rtscts (or dtrdsr). The result is unpredictable. πŸ’€ The -ttycontrol option cannot be queried.
  • -ttystatus β€” (Windows and Unix). The -ttystatus option can only be queried. It returns the current modem status and handshake input signals (see below). The result is a list of signal,value pairs with a fixed order, e.g. {CTS 1 DSR 0 RING 1 DCD 0}. The signal names are returned upper case. πŸ”₯
  • -xchar {xonChar xoffChar} β€” (Windows and Unix). This option is used to query or change the software handshake characters. Normally the operating system default should be DC1 (0x11) and DC3 (0x13) representing the ASCII standard XON and XOFF characters.
  • -closemode closeMode β€” (Windows and Unix). This option is used to query or change the close mode of the serial channel, which defines how pending output in operating system buffers is handled when the channel is closed. The following values for closeMode are supported:
    • default β€” indicates that a system default operation should be used; all serial channels default to this.
    • discard β€” indicates that the contents of the OS buffers should be discarded.
Note that this is not recommended when writing to a POSIX terminal, as it can interact unexpectedly with handling of stderr. 😭
  • drain β€” indicates that Tcl should wait when closing the channel until all output has been consumed. This may slow down close noticeably. 🐌

to be continued, bestie β€” more parts incoming πŸ’–βœ¨

  • -inputmode inputMode β€” (Unix only; Windows has the equivalent option on console channels). Bestie, this one lets you query or change the input mode of the serial channel β€” it's assuming the channel is talking to a terminal, which is what controls how interactive user input gets handled. Here's the whole menu of inputMode values you can throw at it:
    • normal β€” the chill default vibe: normal line-oriented input, with all the standard terminal editing capabilities turned on. ✨
    • password β€” non-echoing input. Standard terminal editing is still enabled, but nothing you type gets written back to the terminal (except newlines). Some terminals might flag this specially. 🫣
    • raw β€” no filter, no processing, all keyboard input goes straight to Tcl and the terminal does literally nothing. It doesn't even echo your keys β€” interpreting what to do is 100% on the Tcl script. πŸ’…
    • reset (set only) β€” tells the terminal to go back to whatever state it was in when it was opened. It's giving "undo my whole era". πŸŽ€
Heads up: setting this option (technically, anything that changes the terminal state from its initial value through this option) makes the channel turn on an automatic reset of the terminal when the channel is closed. So it cleans up after itself. Iconic behaviour, ngl.
  • -winsize β€” (Unix only; Windows has the equivalent option on console channels). This one is query only β€” it just hands you back a two-element list with the current width and height of the terminal. πŸ“
  • -pollinterval msec β€” (Windows only). This sets the maximum time between polling for fileevents. It affects the time interval between checking for events across the whole Tcl interpreter (the smallest value always wins). Only reach for this if you wanna poll the serial port more or less often than 10 msec, which is the default. ⏱️
  • -sysbuffer inSize
  • -sysbuffer {inSize outSize} β€” (Windows only). This changes the size of the Windows system buffers for a serial channel. Especially at higher communication rates, the default input buffer size of 4096 bytes can overrun on latent systems 😭. First form = just the input buffer size; second form = both input and output buffers get defined. 🧺
  • -lasterror β€” (Windows only). Query only, bestie. If a serial communication error happens, read or puts returns a general Tcl file I/O error. That's when you call fconfigure -lasterror to get a list of error details. The various error codes are explained below πŸ‘‡.

✨ SERIAL PORT SIGNALS ✨

RS-232 is the most commonly used standard electrical interface for serial communications, no cap. A negative voltage (-3V..-12V) defines a mark (on=1) bit, and a positive voltage (+3..+12V) defines a space (off=0) bit (RS-232C). The following signals are specified for incoming and outgoing data, status lines, and handshaking. 🫢

Here we're using the term workstation for your computer and modem for the external device, because some signal names (DCD, RI) literally come from modems. Of course your external device might be using these signal lines for something totally different β€” it's giving "borrowed terminology" energy. πŸ’€

  • TXD (output) β€” Transmitted Data: outgoing serial data. πŸ“€
  • RXD (input) β€” Received Data: incoming serial data. πŸ“₯
  • RTS (output) β€” Request To Send: this hardware handshake line tells the modem that your workstation is ready to receive data. Your workstation may automatically reset this signal to indicate that the input buffer is full. 🈡
  • CTS (input) β€” Clear To Send: the complement to RTS. Indicates the modem is ready to receive data. βœ…
  • DTR (output) β€” Data Terminal Ready: this signal tells the modem the workstation is ready to establish a link. DTR is often enabled automatically whenever a serial port is opened. πŸ”—
  • DSR (input) β€” Data Set Ready: the complement to DTR. Tells the workstation the modem is ready to establish a link. 🀝
  • DCD (input) β€” Data Carrier Detect: this line goes active when a modem detects a "Carrier" signal. πŸ“‘
  • RI (input) β€” Ring Indicator: goes active when the modem detects an incoming call. ☎️
  • BREAK β€” lowkey not a hardware signal line at all! It's a logical zero on the TXD or RXD lines for a long period of time, usually 250 to 500 milliseconds. Normally a receive or transmit data signal just sits at the mark (on=1) voltage until the next character comes through. A BREAK is sometimes used to reset the communications line or switch up the operating mode of communications hardware. πŸ›‘

πŸ’€ ERROR CODES πŸ’€ (Windows only)

A lot of different errors can pop off during serial read operations or during event polling in the background. The external device might've been switched off, the data lines might be noisy, system buffers might overrun, or your mode settings might just be wrong. That's exactly why reliable software should always catch serial read operations. 😀

When an error happens, Tcl returns a general file I/O error. Then fconfigure -lasterror can help you locate the problem. These are the error codes that may come back:

  • RXOVER β€” Windows input buffer overrun. The data comes in faster than your script reads it, or your system is overloaded. Use fconfigure -sysbuffer to avoid a temporary bottleneck and/or make your script faster. πŸƒβ€β™€οΈ
  • TXFULL β€” Windows output buffer overrun. The complement to RXOVER. This error should practically never happen, because Tcl actually cares about the output buffer status. 🫑
  • OVERRUN β€” UART buffer overrun (hardware) with data lost. The data comes faster than the system driver receives it. Check your advanced serial port settings to enable the FIFO (16550) buffer and/or setup a lower(1) interrupt threshold value. πŸ•³οΈ
  • RXPARITY β€” a parity error has been detected by your UART. Wrong parity settings with fconfigure -mode or a noisy data line (RXD) may cause this. 🎭
  • FRAME β€” a stop-bit error has been detected by your UART. Wrong mode settings with fconfigure -mode or a noisy data line (RXD) may cause this one too. πŸ–ΌοΈ
  • BREAK β€” a BREAK condition has been detected by your UART (see above). πŸ›‘

🌍 PORTABILITY ISSUES 🌍

Windows

Valid values for fileName to open a serial port are of the form comX, where X is a number, generally from 1 to 9. A legacy form that's also accepted is comX: β€” but bestie, that notation only works for serial ports 1 to 9. If you try to open a serial port that doesn't exist or has a number greater than 9, it will fail. 😭

An alternate form of opening serial ports is to use the filename //./comX, where X is any number that corresponds to a serial port. 🎟️

When running Tcl interactively, there may be some strange interactions between the real console (if one is present) and a command pipeline that uses standard input or output. If a command pipeline is opened for reading, some of the lines you type at the console get sent to the command pipeline and some get sent to the Tcl evaluator. πŸ˜΅β€πŸ’« If a command pipeline is opened for writing, keystrokes entered into the console are not visible until the pipe is closed. These problems only happen because both Tcl and the child application are fighting over the console at the same time β€” it's giving "two main characters, one microphone". 🎀 If the command pipeline is started from a script (so Tcl isn't touching the console), or if the pipeline doesn't use standard input or output but is redirected from or to a file, then the above problems don't occur. ✨

Files opened in the "a" mode or with the APPEND flag set are implemented by seeking immediately before each write, which is not an atomic operation and does not carry the guarantee of strict appending that's present on POSIX platforms. ⚠️

Unix

Valid values for fileName to open a serial port are generally of the form /dev/ttyX, where X is a or b, but honestly the name of any pseudo-file that maps to a serial port may be used. Advanced configuration options are only supported for serial ports when Tcl is built to use the POSIX serial interface. 🐧

When running Tcl interactively, there may be some strange interactions between the console (if one is present) and a command pipeline that uses standard input. If a command pipeline is opened for reading, some of the lines entered at the console get sent to the command pipeline and some get sent to the Tcl evaluator. Same "competing for the console" situation as above. 😭 If the command pipeline is started from a script (so Tcl isn't accessing the console), or if the pipeline doesn't use standard input but is redirected from a file, then the above problem doesn't occur. 🌸

See the PORTABILITY ISSUES section of the exec command for additional information β€” not specific to command pipelines β€” about executing applications on the various platforms. πŸ“š

πŸ–₯️ CONSOLE CHANNELS πŸ–₯️

okay bestie, listen β€” this whole section is Windows only, no cap. Console channels (which is usually just stdin or stdout) support these two extra options, and only these two:

  • -inputmode inputMode β€” this one lets you ask about or change the input mode of the console channel, which is basically the vibe-check on how interactive typing from users gets handled. Here's what you can pass for inputMode:
    • normal β€” standard line-oriented input, with all the normal console editing stuff turned on. It's giving default behavior, it's giving nothing weird.
    • password β€” non-echoing input. You still get the standard console editing capabilities, but literally nothing you type gets written to the terminal (except newlines, those still show). Secretive. Mysterious. Iconic.
    • raw β€” ALL keyboard input goes straight to Tcl and the console does zero processing. It does not echo the keys at all, so it's fully on your Tcl script to figure out what to do with them. Main character energy, but the script has to carry the whole plot.
    • reset (set only) β€” puts the console back to whatever state it was in when the console channel was first opened. Rewind. Undo. Slay.
heads up: setting this option β€” technically, anything that changes the console state away from its default via this option β€” makes the channel turn on an automatic reset of the console when the channel gets closed. So it cleans up after itself whether you remembered or not. 🫢
  • -winsize β€” this one is query only. It hands you a two-element list with the current width and height of the console this channel is talking to. Just a lil peek at the dimensions, no writing. πŸ‘€

ngl there's a plot twist here: the equivalent options do exist on Unix too, but they live on the serial channel type instead. iykyk.


✨ EXAMPLES ✨

okay these are the fun ones, let's go πŸŽ€

Open a file for writing, forcing it to be created and raising an error if it already exists.

set myNewFile [open filename.txt {WRONLY CREAT EXCL}]

Open a file for writing as a log file.

set myLogFile [open filename.log "a"]
fconfigure $myLogFile -buffering line

Open a command pipeline and catch any errors:

set fl [open "| ls this_file_does_not_exist"]
set data [read $fl]
if {[catch {close $fl} err]} {
    puts "ls command failed: $err"
}

Open a command pipeline and read binary data from it. Note the unusual form with |[list β€” that handles the non-trivial edge cases where your arguments might have spaces in them. lowkey a lifesaver fr fr.

set fl [open |[list create_image_data $input] "rb"]
set binData [read $fl]
close $fl

Read a password securely from the user (this assumes the script is being run interactively, okay? don't come for me):

chan configure stdin -inputmode password
try {
    chan puts -nonewline "Password: "
    chan flush stdout
    set thePassword [chan gets stdin]
} finally {
    chan configure stdin -inputmode reset
}

see how it resets in the finally? that's the good manners. that's the etiquette. we love to see it. πŸ’…


πŸ‘€ SEE ALSO πŸ‘€

your reading list, bestie, go be curious:


πŸ”‘ KEYWORDS πŸ”‘

the search terms, the tags, the algorithm fuel ✨

access mode, append, create, file, non-blocking, open, permissions, pipeline, process, serial


and that's the whole page, babes 🌈 this one came straight out of the Tcl 8.3 manual β€” it's the open(3tcl) page, and yeah the version is giving vintage but the knowledge is timeless πŸ’– go open some files responsibly, mwah πŸŽ€

πŸ“¦ where this page comes from