python - 波浪号 (~) 在 subprocess.Popen() 中不起作用

标签 python subprocess popen dd

当我在我的 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/

相关文章:

python - tkinter 的 .pack_propagate() 方法

python - 如何仅读取和删除特定行的代码?

python - 当多处理 Python 关闭时外部程序正在运行

Python:子进程并运行具有多个参数的 bash 脚本

python-2.7 - 尝试通过 Popen() 使用 Python 发送 EOF 信号(Ctrl+D)信号

python - django中通过form更新DB数据

python - 使用 psycopg2 为 Postgres 转义 SQL "LIKE"值

python - 在 foreach 循环中运行多个子进程?一次一个?

python - FileNotFoundError : [Errno 2] No such file or directory: 'bash' when running gunicorn server from . 服务文件

python - 杀死使用 Python 的 subprocess.Popen() 创建的进程