Skip to content

Instantly share code, notes, and snippets.

@jhlb
Last active April 19, 2023 20:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jhlb/83999422a8d7e8a6e28e to your computer and use it in GitHub Desktop.
Save jhlb/83999422a8d7e8a6e28e to your computer and use it in GitHub Desktop.
progbar.py : Print current position in file versus file length.
#!/bin/env python
import sys, os
USAGE="""
./progbar.py PROCESS_ID [FILE_DESCRIPTOR_NUMBER]
Usage:
./progbar.py PROCESS_ID
Prints all file descriptor numbers along with the path of
each.
./progbar.py PROCESS_ID FILE_DESCRIPTOR_NUMBER
Prints the current seek location of the process in the
file, the total length of the file, and the current
location versus the end as a percentage.
"""
def print_file_descriptors(pid):
fd_dir = os.path.join('/proc', pid, 'fd')
fds = os.listdir(fd_dir)
for fd in fds:
print fd, "=>", os.readlink(os.path.join(fd_dir, fd))
def print_current_position(pid, fd):
# step 1: get current location
fdinfo_filename = os.path.join('/proc', pid, 'fdinfo', fd)
fdinfo_handle = file(fdinfo_filename)
location = int(fdinfo_handle.readlines()[0].split()[1])
fdinfo_handle.close()
# step 2: get total size.
file_path = os.readlink(os.path.join('/proc', pid, 'fd', fd))
size = os.stat(file_path).st_size
# report
print location, "/", size
print "%.2f%%" % (float(location)/float(size)*100)
def main():
if len(sys.argv) == 2:
# Case 1: Print all file descriptor numbers and filenames.
pid = sys.argv[1]
print_file_descriptors(pid)
elif len(sys.argv) == 3:
# Case 2: Print the location of the file pointer, this file size,
# and the percentage of the file behind the file pointer.
pid = sys.argv[1]
fd = sys.argv[2]
print_current_position(pid, fd)
else:
# Case 3: Print usage and exit
print USAGE
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment