Dimmi le dimensioni della mia console!


41

Dimensioni del terminale di output (colonne e righe) in qualsiasi formato decimale a due numeri *. Ad esempio, un output potrebbe essere 80x25.


Ispirazione . Pronto .
* L'output deve avere entrambe le misure su una o due righe consecutive e potrebbe non esserci più di una riga di output iniziale e / o finale (facoltativamente seguita da una nuova riga). Le (fino a quattro) righe non devono essere più lunghe di max (cols, 1 + len (str (cols)) + len (str (ro‌ws))).


2
Non ho mai visto una sfida più breve votata. Congratulazioni!
Mr. Xcoder,

13
@ Mr.Xcoder Sono specializzato in one-liner ...
Adám,

Stai per ottenere una laurea in posti con una sola fila! Sei davvero bravo, no, molto bravo in questo
:)

cosa significa esattamente "formato coerente"?
Felipe Nardi Batista,

1
@FelipeNardiBatista Dirò di sì per ora, ma tornerò se questo porta ad assurdità.
Adám,

Risposte:


27

* sh, 9

stty size

Produzione:

97 364

Funziona anche in bash.
numbermaniac,

2
O qualsiasi altra shell su un sistema simile a posix.
mvds

1
Dati i nomi di alcune lingue visualizzate su questo sito, ci vuole più tempo per capire che * sh qui si riferisce a "bash, zsh, csh, dash, ecc." piuttosto che una lingua il cui nome è costituito da un asterisco seguito dalle lettere se h :-)
ShreevatsaR

Tecnicamente non hai nemmeno bisogno di una shell per eseguire un programma. Quindi la shdesignazione non ha davvero senso comunque.
mvds,

20

8086 codice macchina, 11 byte (come funzione, non concorrenziale)

Non è davvero in competizione poiché non ha un output visibile. Questo sta solo mostrando il modo più breve per trovare le dimensioni attuali dello schermo, senza il codice della caldaia richiesto per la stampa.

00000000  6a 40 1f a0 84 00 40 8a  26 4a 00                 |j@....@.&J.|
0000000b

Come funziona:

6a 40           |   push 0x40       ; bios data segment
1f              |   pop ds
a0 84 00        |   mov al, [0x84]  ; console rows - 1
40              |   inc ax
8a 26 4a 00     |   mov ah, [0x4a]  ; console columns

8086 codice macchina, 48 byte (come programma completo)

00000000  1f bf 30 01 a0 84 04 40  e8 1a 00 b0 78 aa a0 4a  |..0....@....x..J|
00000010  04 e8 11 00 8d 8d d0 fe  8d 75 ff 06 1f fd ac cd  |.........u......|
00000020  29 e2 fb cd 20 d4 0a 0c  30 aa c1 e8 08 75 f6 c3  |)... ...0....u..|
00000030

Come funziona:

                |   org 0x100
                |   use16
1f              |       pop ds              ; clear ds (the stack always contains 0 on entry)
bf 30 01        |       mov di, d           ; set destination ptr
a0 84 04        |       mov al, [0x484]     ; console rows - 1
40              |       inc ax
e8 1a 00        |       call to_ascii       ; convert to ascii
b0 78           |       mov al, 'x'
aa              |       stosb
a0 4a 04        |       mov al, [0x44a]     ; console columns
e8 11 00        |       call to_ascii
8d 8d d0 fe     |       lea cx, [di-d]      ; number of characters to print
8d 75 ff        |       lea si, [di-1]      ; set source ptr
06              |       push es
1f              |       pop ds
fd              |       std                 ; reverse direction flag
ac              |   @@: lodsb               ; load (al = *si--)
cd 29           |       int 0x29            ; print al to console, bypassing stdout
e2 fb           |       loop @b             ; repeat while (--cx != 0)
cd 20           |       int 0x20            ; terminate
                |   
                |   to_ascii:
d4 0a           |       aam 10              ; ah = (al / 10), al = (al % 10)
0c 30           |       or al, 0x30         ; convert al to ascii number
aa              |       stosb               ; store (*di++ = al)
c1 e8 08        |       shr ax, 8           ; shift ah to al
75 f6           |       jnz to_ascii        ; repeat if non-zero
c3              |       ret
                |   
                |   d rb 0

Sono abbastanza sicuro che un invio di una funzione avrebbe bisogno di un ret? Inoltre, non sono sicuro che ti sia permesso di ostruire ds. Potrebbe essere necessario portarlo su Meta, poiché la funzione funziona più di una volta, ha solo effetti collaterali indesiderati.

Perché "lo stack contiene sempre 0 all'entrata"? Non conosco alcuna regola per cui lo stack viene azzerato. Immagino che stai parlando di far scattare il valore di ritorno e pensare che sarà 0? È garantito per un binario COM?
Cody Gray

@CodyGray: in un programma COM, lo stack inizialmente contiene un puntatore vicino all'inizio della PSP (offset 0), quindi RET tornerà a PSP: 0, che contiene una chiamata a EXIT. stackoverflow.com/a/12593311/371250
ninjalj

Ah, grazie per il chiarimento, @ninjalj. (Ottima risposta che hai collegato, BTW. Avevo dimenticato praticamente tutti i dettagli sulla PSP, nonostante avessi ingegnerizzato la sua implementazione molti anni fa.) Ma se togli quel puntatore dallo stack senza respingerlo, non farlo hai rotto le RETistruzioni alla fine della funzione?
Cody Gray,

@CodyGray: noterai che il programma esce via INT 20h, non via RET, esattamente perché dopo che POPing esce tramite RETnon funziona più.
ninjalj,

18

Bash, 22 20 caratteri

echo $COLUMNS $LINES

Grazie a:

  • Maniglia della porta per un formato di output ottimale (2 caratteri)

Esecuzione di esempio:

bash-4.3$ echo $COLUMNS $LINES
80 24

Con solo 1 byte in più, echo $COLUMNS\x$LINESpuò o / p80x24
Pandya,

@Pandya Vero, ma non necessario.
Adám,

7
Non sono sicuro che ciò sia conforme ai nuovi requisiti del formato di output, ma potresti semplicemente avere $ COLUMNS \ x $ LINES per generare "bash: 90x50: comando non trovato". Supponiamo che non funzioni con la localizzazione, o se quel comando esiste davvero !.
Muzer,

14

xterm, 6 byte

Poiché non hai bisogno di un formato specifico, puoi semplicemente usare il resizecomando (6 caratteri) di xterm:

$ resize
COLUMNS=120;
LINES=31;
export COLUMNS LINES;

1
Bello. Ma potresti voler scrivere un'intestazione standard, come #xterm, 6 bytes.
Adám,

@ Adám Questo tipo di output è accettabile in base alla domanda?
Pandya,


@ Adám ok. Appena aggiunto header :)
Pandya,

Questo non è specifico per xterm. Nota anche che l'output dipende dalla tua shell.
Celtschk,

13

sh, 20 byte

tput lines;tput cols

.. Troppo ovvio, forse ..


3
tput cols; !: 0 cols salva un byte in bash
marcosm,

@marcos intendi tput lines;!:0 cols, vero?
Dieter,

12

Python 3 , 30 byte

import os
os.get_terminal_size

Poiché non funziona in TIO, viene utilizzata un'alternativa lì:

Provalo online!


1
Perché non solo os?
Jonathan Allan,

2
... non funzionerà su TIO, a causa del sistema operativo, quindi è necessario specificare. Si fa il lavoro su Windows. Inoltre import osed os.è più corto di from....
Jonathan Allan,

Posso confermare che funziona su Windows 10 senza alcuna modifica
Ferrybig,

Funziona anche su Mac
Mr. Xcoder

1
Tecnicamente Python 3.3+
matsjoyce,

11

C (solo Linux), 63 61

short m[4];main(){ioctl(0,21523,m);printf("%dx%d",*m,m[1]);}

4
You could win two bytes by replacing m[0] by *m.
YSC

You can save one byte by making m an argument of main: main(short m){ioctl(0,21523,&m);printf("%dx%d",m,(&m)[1]);}
mvds

main(int m){ioctl(0,21523,&m);printf("%x",m);} would be 46 bytes, with sizes printed in base 16 and no separator (other than possible leading zeroes) between cols and rows.
mvds


8

C#, 59 bytes

using c=System.Console;_=>c.WindowWidth+"x"+c.WindowHeight;

Compiles to a Func<int, string, however, the input is not used.


Does not work; I found this returns the size the console would be if AllocConsole() were called, not the size the console standard input and output are actually connected to. Question here: stackoverflow.com/questions/35688348/… What I held back when asking the question is I was actually running on a Windows environment with stdin & stdout connected to a ssh pipeline. The win32 ssh implementation does not provide the necessary.
Joshua

7

NodeJS, 50 48 46 bytes

> s=process.stdout;console.log(s.columns,s.rows)
80 25

Uses process.stdouts columns and rows values.


Thanks @ETHproductions, added console.log to output to console :)
Pete TNT

No problem :-) The output can be in any consistent format, so I think you can save a couple bytes by doing console.log([s.columns,s.rows]).
ETHproductions

5
1 byte off: with(process.stdout)console.log(columns,rows)
Brian McCutchon

1
And a few more bytes off (if this counts): with(process.stdout)write(columns+[rows]). Or, if it doesn't count: with(process.stdout)write(columns+' '+rows)
markasoftware

1
@Markasoftware Ooh, that's clever. I don't think the first one should count, though.
Brian McCutchon

6

Ruby, 41 36 21 + 13 = 34 bytes

Run with the command line flag -rio/console

p IO.console.winsize

This is my first Ruby golf, so tell me if there is anything I can do better.

5 bytes saved thanks to SztupY

2 bytes saved thanks to manatwork


This outputs height then width as a length two list.

Example output:

[25, 80]

you can potentially move the requires into the -r command line parameter which is only 2 extra bytes
SztupY

No need for the single quotes around io/console, no shell will perform undesired expansion on it if left unquoted.
manatwork

6

GNU Forth, 7 bytes

form .s

form – urows ucols gforth “form”

The number of lines and columns in the terminal.

Sample Output

<2> 24 80

Try It Online !


4

C# 94 bytes (whole app)

MetaColon's whole app answer can be shortened quite a lot:

using c=System.Console;class P{static void Main(){c.Write(c.WindowWidth+' '+c.WindowHeight);}}

4

PowerShell + Mode, 11 Bytes?

Output may not be acceptable in current form.

the mode command is a default windows utility

Meta Post regarding usage of mode without specifying con

(mode)[3,4]

gets the output of mode:

<Whitespace>
Status for device CON:
----------------------
    Lines:          3000
    Columns:        120
    Keyboard rate:  31
    Keyboard delay: 1
    Code page:      850

then the 4th & 5th lines ([3,4]) outputting:

PS H:\> (mode)[3,4]
    Lines:          3000
    Columns:        120

Save two bytes: (mode)[3,4]-replace"\D"
Adám

for this to work here, i need to use (mode con)[3..4]
Felipe Nardi Batista

Ah @FelipeNardiBatista is probably right that you need con.
Adám

1
@FelipeNardiBatista is con neccessary? this gets the first lines absolutely, and I believe con is always first? i'd say a standard system will also only have one output for mode, which is what we should assume?
colsw

1
@ConnorLSW It's just that my system does work fine, but your answer simply doesn't work here
Felipe Nardi Batista

4

Swift, 99 bytes

import Foundation;var w=winsize();ioctl(STDOUT_FILENO,UInt(TIOCGWINSZ),&w);print(w.ws_col,w.ws_row)

Thanks to the guys at Vapor for their Console package.


3

Batch, 25 19 18 17 bytes

Saved 6 bytes by piping directly to the "find" command.
Saved 1 byte thanks to Adám / OP.
Saved 1 byte thanks to comment by OP.

mode con|find "n"

This outputs the command itself since echo is on but, as commented by OP, a leading line is OK.


Depending on your setup, it may work with only 13 bytes. However, it seems that having anything using COM ports will cause overly verbose output.

mode|find "n"

Save a byte s:n.
Adám

1
@FelipeNardiBatista Yeah, and mine says I've got 9001 lines. It's just a setting: Properties>Layout>Screen Buffer Size.
Adám

@FelipeNardiBatista Windows console dimensions are not the same as the window dimensions. That's why scroll bars show up when you make the window smaller. Per OP, this exact solution is OK.
Engineer Toast

@Adám Dangit, I looked for a shorter string and don't know how I overlooked it. It's probably because I started with just mode but found that adding ` con` was shorter than looking for two different sets of characters with findstr.
Engineer Toast

@Adám Based on your comment, would this be valid: @mode|find "L" /i ? It returns Lines, Columns, and Keyboard Delay with 17 bytes instead of the 18 above. Do those leading / trailing lines need to be empty?
Engineer Toast

3

C#, 85 Bytes

()=>System.Console.Write(System.Console.WindowWidth+"x"+System.Console.WindowHeight);

If you want a whole application code, we'd have 115 101 94 Bytes:

using C=System.Console;class P{static void Main()=>C.Write(C.WindowWidth+"x"+C.WindowHeight);}

However you could mean the Buffer size as well, we'd have 85 Bytes again

()=>System.Console.Write(System.Console.BufferWidth+"x"+System.Console.BufferHeight);

Or as a whole application code (obviously 115 101 94 Bytes again):

using C=System.Console;class P{static void Main()=>C.Write(C.BufferWidth+"x"+C.BufferHeight);}

Saved 14 Bytes in the whole application code with the help of Caius Jard


1
104 bytes whole app, perhaps you can extend the logic to your other variations: using c=System.Console;class P{static void Main(){c.WriteLine(c.WindowWidth);c.Write(c.WindowHeight);}}
Caius Jard

(I'm not sure how to golf if I have a shorter answer; do i edit yours, comment yours, or post my own?)
Caius Jard

@CaiusJard You could post your own answer or comment an improvement and let the answerer decide if they want to incorporate it or not.
TheLethalCoder

I wanted to, just couldn't edit my comment in time... Posted my own answer (that included it) virtually simultaneously though so I prmise I wasn't nicking your inspiration :). Not too sure whether I feel it's cheating to essentially be writing a function that returns the answer, rather than a whole app - all the other answers are pretty much a whole app, but then again CSharppPad.com will accept your "sole function" version and run it.. should look up the rules on golfing i guess
Caius Jard

@CaiusJard Functions/methods are allowed implicitly unless explicitly disallowed in the challenge itself. Therefore, an anonymous function is fine, see my answer for a version that works well.
TheLethalCoder

2

Java 8 (no libraries), Windows, 270 bytes

Posting seperately by recommendation of Adam.

interface B{static void main(String[] a)throws Exception{Object[]r=new java.io.BufferedReader(new java.io.InputStreamReader(Runtime.getRuntime().exec("cmd /c mode").getInputStream())).lines().toArray();System.out.print(r[3]+"\n"+r[4]);}}

Ungolfed:

interface B {
    static void main(String[] a) throws Exception {
        Object[] r = new java.io.BufferedReader(new java.io.InputStreamReader(
                Runtime.getRuntime().exec("cmd /c mode").getInputStream())
        ).lines().toArray();
        System.out.print(r[3] + "\n" + r[4]);
    }
}

Try cmd/c mode instead of cmd /c mode.
Conor O'Brien

Just tried, Runtime.exec() interprets that as trying to execute cmd/c resulting in CreateProcess error=2. :(
F. George

2

8th, 24 16 12 bytes

Revised after Anders Tornblad comment.

con:size? .s

Returns the current size of the console in rows and columns printing stack content.

Output:

2  n: 000000000285e5e0 1   300
1  n: 000000000285e4c0 1   90

2
Since the question allows any output format, do you really need swap?
Anders Tornblad

@Anders Tornblad - Thank you for your wise comment. I improved my code.
Chaos Manor

2

Java + *nix, 113

interface B{static void main(String[] a)throws Exception{new ProcessBuilder("stty","size").inheritIO().start();}}

Ungolfed:

interface B{
    static void main(String[] a)throws Exception{
        new ProcessBuilder("stty","size").inheritIO().start();
    }
}

ProcessBuilder.inheritIO causes a child process input/output to be inherited; this is the default in C with exec. In Java, the default is "piped." As you can see, this is way shorter than using Runtime.getRuntime().exec() (which is also deprecated) and constructing a BufferedReader through a long and convoluted call that is the result of the Java API designers' apparent unwillingness to add an overload for convenience.


I wish ProcessBuilder would work on Windows, but the mode command outputs more than 4 lines :(
F. George

1

Red, 19 Bytes

system/console/size

Output:

>> system/console/size
== 106x26

Can also get the screen resolution as in the previous question


1

Commodore 64 BASIC, 7 bytes

?"40x25

The C64 has a fixed-size text console of 40 x 25 characters. It is not necessary to query the console size, which is a good thing, as there is no way to query it.


This seems like cheating, although to be fair, the question (nor its inspiration) does not specifically prohibit it.
Cody Gray


1

Kotlin + Jline 2, 58 bytes

{print(jline.TerminalFactory.get().run{"$width $height"})}

Because why not. Turns out the standard lib actually has no way to determine console size so pulling in a library is required, lest you want to gold launching another process and parsing the input stream... would be a shame if somebody did that..


Don't put two answers in one post.
Adám

@Adám It's more of an afterthought, so I think it's fine. You have enough rep to edit it directly, do so if you really believe a 270b with arbitary restrictions should be a seperate answer.
F. George

Each submission competes against other submissions in the same language. Java is inherently verbose, but yours is the shortest (and only) Java submission. Also, while I can edit your post, I cannot post a separate answer in your name.
Adám

I was implicating that if you remove my Java answer, I will repost it myself. And while you have a point that the answer is currently the shortest Java answer, it is coded under restriction of using no external libraries. In order to address your argument, I will mark it as non-competing and code a proper Java answer later.
F. George

Post it as Java (no libraries) and make another submission called Java with …. That will get you three upvotes from me.
Adám

1

Stacked, 7 bytes

termdim

Leaves output on the stack, as is allowed per default. Example usage:

λ stacked -pe "termdim"
(117 26)

Bonus: termdim'x'#` to have it 117x26.


1

C (linux, C89 only), 45 41

inspired by https://codegolf.stackexchange.com/a/118696/42186 by @dieter

main(m){ioctl(0,21523,&m);write(1,&m,4);}

this outputs the size as binary data. Not sure if this counts as "any format". You would need something extra (less, hexdump, od, ascii table) (or an esoteric terminal emulator that automatically does this for you) to make it human readable. Example usage:

$ ./a.out | od -sAn
     58    204

The terminal size is 204 cols by 58 rows.

Thanks to @Random832 for using od instead of hexdump.


1
I think hex is pushing it. All other answers use decimal, so I'm going to add this requirement to OP. Sorry.
Adám

1
od -s will do it in decimal and is shorter than hexdump
Random832

@Random832 Cool, didn't know that, +1! But this answer became invalid anyway, when the rules changed from "any format" to a very specific format (something like: base 10 in ascii in mainstream terminal emulators)
mvds
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.