当我在我的 Ubuntu 终端中运行时:
sudo dd if=/dev/sda of=~/file bs=8k count=200k; rm -f ~/file
它工作正常。
如果我通过 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
这是行不通的。我得到的错误是:
dd: failed to open '~/disk_benchmark_file': No such file or directory
如果我在 Popen()
中将波浪号 ~
更改为 /home/user
,那么它就可以工作了!
为什么会这样? 对我来说更重要的是:我怎样才能让它发挥作用? 我不知道生产中的用户名是什么。
最佳答案
你需要用 os.path.expanduser()
包裹这些路径名:
>>> import os
>>> os.path.expanduser('~/disk_benchmark_file')
'/home/dan/disk_benchmark_file'
在您的代码中出现:
['sudo', 'dd', 'if=/dev/' + disk, 'of=~/disk_benchmark_file', 'bs=8k', 'count=200k']
应该替换为:
['sudo', 'dd', 'if=/dev/' + disk, 'of=' + os.path.expanduser('~/disk_benchmark_file'), 'bs=8k', 'count=200k']
关于python - 波浪号 (~) 在 subprocess.Popen() 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40662821/