pythonsubprocesspopendd

Tilde (~) isn't working in subprocess.Popen()


When I run in my Ubuntu terminal:

sudo dd if=/dev/sda of=~/file bs=8k count=200k; rm -f ~/file

it works fine.

If I run it through Pythons subprocess.Popen():

output, err = subprocess.Popen(['sudo', 'dd', 'if=/dev/' + disk, 'of=~/disk_benchmark_file', 'bs=8k', 'count=200k'], stderr=subprocess.PIPE).communicate()
print err

it doesn't work. The Error I get is:

dd: failed to open '~/disk_benchmark_file': No such file or directory

If I change in the Popen() call the tilde ~ to /home/user, then it works!

Why is it like that? And more important to me: How can I make it work? I don't know what the user name will be in production.


Solution

  • You need to wrap those pathnames with os.path.expanduser():

    >>> import os
    >>> os.path.expanduser('~/disk_benchmark_file')
    '/home/dan/disk_benchmark_file'
    

    In your code the occurrence of:

    ['sudo', 'dd', 'if=/dev/' + disk, 'of=~/disk_benchmark_file', 'bs=8k', 'count=200k']
    

    should be replaced with:

    ['sudo', 'dd', 'if=/dev/' + disk, 'of=' + os.path.expanduser('~/disk_benchmark_file'), 'bs=8k', 'count=200k']