Skip to content

Instantly share code, notes, and snippets.

@Steelsouls
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Steelsouls/9626112 to your computer and use it in GitHub Desktop.
Save Steelsouls/9626112 to your computer and use it in GitHub Desktop.
Function to return width of terminal running the script. Perfect for CLI apps in determining available space for formatting output data. If run as a script simply prints the number.
#!/usr/bin/env python
import subprocess
command = ['tput', 'cols']
def get_terminal_width():
try:
width = int(subprocess.check_output(command))
except OSError as e:
print("Invalid Command '{0}': exit status ({1})".format(
command[0], e.errno))
except subprocess.CalledProcessError as e:
print("Command '{0}' returned non-zero exit status: ({1})".format(
command, e.returncode))
else:
return width
def main():
width = get_terminal_width()
if width:
print(width)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment