Lyc*_*cea 0 python linux subprocess popen python-3.x
我有一个小问题。我在 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")
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时,我收到以下错误:
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: '~'
Run Code Online (Sandbox Code Playgroud)
我不确定我做错了什么,因为当您在 cd 命令中输入 ~ 时,它会将您切换到主目录。我希望有人能找到解决方案,解释为什么它不能以这种方式工作,以及在主目录中启动它的正确方法是什么。
为了清楚起见,我简化了您的代码。
使用 Python 3.6 或更高版本,您可以执行以下操作:
import subprocess, pathlib
subprocess.Popen(['echo', 'test'], cwd=pathlib.Path.home())
Run Code Online (Sandbox Code Playgroud)
使用Python 3.5,您需要包装Path.home()成str():
import subprocess, pathlib
subprocess.Popen(['echo', 'test'], cwd=str(pathlib.Path.home()))
Run Code Online (Sandbox Code Playgroud)
对于任何低于 3.5 的 Python 版本,您可以使用:
import os, subprocess
subprocess.Popen(['echo', 'test'], cwd=os.path.expanduser('~'))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4901 次 |
| 最近记录: |