Search code examples
pythonsubprocesspopen

How to communicate with parted interpreter via python?


from subprocess import Popen,PIPE,STDOUT

a=Popen('parted -s',stdout = PIPE, stderr = STDOUT, shell = True)
a.communicate(input="print".encode())
string=a.stdout.read()

I want to use the "print" command within parted, how do I do so?


Solution

  • You can achieve this without sending input to the child's stdin, just use the command line and execute it with subprocess.check_output():

    import shlex
    import subprocess
    
    DEVICE = '/dev/sda'
    cmd = 'parted -s {} print'.format(DEVICE)
    
    output = subprocess.check_output(shlex.split(cmd))
    
    >>> print output
    Model: ATA Hitachi HTS54756 (scsi)
    Disk /dev/sda: 640GB
    Sector size (logical/physical): 512B/4096B
    Partition Table: msdos
    Disk Flags: 
    
    Number  Start   End    Size   Type      File system  Flags
     1      1049kB  210MB  209MB  primary   ntfs         boot
     2      210MB   322GB  322GB  primary   ntfs
     4      322GB   640GB  318GB  extended
     5      322GB   322GB  524MB  logical   ext4
     6      322GB   640GB  318GB  logical                lvm
     3      640GB   640GB  108MB  primary   fat32        lba