python 子进程 popen 将主目录设置为 cwd

python subprocess popen set home directory as cwd

我有个小问题。我在 ubuntu 16.04 机器上,在 python 脚本中我想启动一个子进程,它应该在用户的主目录中启动。我试过:

subprocess.Popen('echo "Test"', cwd="~", shell=True,universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable="/bin/bash")

但是当我这样做时,出现以下错误:

 proc = subprocess.Popen('echo "test"', cwd="~", shell=True,universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable="/bin/bash")
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: '~'

我不确定自己做错了什么,因为当您在 cd 命令中输入 ~ 时,它会将您 cd 到主目录。我希望有人有解决方案 为什么它不能以这种方式工作以及在主目录中启动它的正确方法是什么。

为了清晰起见,我简化了您的代码。


使用 Python 3.6 或更高版本,您可以执行以下操作:

import subprocess, pathlib
subprocess.Popen(['echo',  'test'], cwd=pathlib.Path.home())

使用 Python 3.5 你需要将 Path.home() 包装成 str():

import subprocess, pathlib
subprocess.Popen(['echo',  'test'], cwd=str(pathlib.Path.home()))

对于低于 3.5 的任何 Python 版本,您可以使用:

import os, subprocess
subprocess.Popen(['echo',  'test'], cwd=os.path.expanduser('~'))