>>> Popen('cd ~', shell=True, stdout=PIPE).communicate()
(b'', None)
没有使用
shell=True
(它在POSIX上以默认方式运行命令,使用的是/bin/sh
)。
>>> Popen(['cd', '~'], stdout=PIPE).communicate()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/subprocess.py", line 858, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1456, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'cd'
>>>
要更改目录,必须通过以下方式进行:
import os
os.chdir(os.path.abspath(os.path.expanduser('~')))
因此问题不在于路径
~
不存在,而是
cd
选项不存在,除非您的命令在支持它的shell中运行。直接传递到实际的shell使
cd
起作用。但请注意,
shell=True
存在风险,除非必要,否则不要使用。
因此,请改用
os.chdir
。
一个可行的方案:
import os, subprocess
os.chdir(os.path.abspath('/tmp/'))
print(subprocess.Popen(['ls', '-lah'], stdout=subprocess.PIPE).communicate()[0].decode('utf-8'))
导致:
[torxed@archie ~]$ python
Python 3.4.1 (default, May 19 2014, 17:23:49)
>>> import os, subprocess
>>> os.chdir(os.path.abspath('/tmp/'))
>>> print(subprocess.Popen(['ls', '-lah'], stdout=subprocess.PIPE).communicate()[0].decode('utf-8'))
total 12K
drwxrwxrwt 9 root root 220 Jun 11 12:08 .
drwxr-xr-x 19 root root 4.0K May 28 08:03 ..
drwxrwxrwt 2 root root 40 Jun 11 09:30 .font-unix
drwx------ 2 torxed users 60 Jun 11 09:33 gpg-LBLcdd
drwxrwxrwt 2 root root 40 Jun 11 09:30 .ICE-unix
drwx------ 2 torxed users 80 Jun 11 09:34 .org.chromium.Chromium.LEqfXB
-rw------- 1 torxed users 153 Jun 11 09:34 serverauth.EHWB0LqCv6
drwxrwxrwt 2 root root 40 Jun 11 09:30 .Test-unix
-r--r--r-- 1 root users 11 Jun 11 09:34 .X0-lock
drwxrwxrwt 2 root root 60 Jun 11 09:34 .X11-unix
drwxrwxrwt 2 root root 40 Jun 11 09:30 .XIM-unix
>>>
注意,我在
~
中启动了shell,并通过
os.chdir
将其更改为tmp目录,实际上获取了我的tmp目录内容。
关于 shell 和命令的解释:
shell 命令是内置于 shell 中的内容,而普通的命令是您可以在
/bin
中找到的东西。
[torxed@archie ~]$ ls /bin
2to3 2to3-2.7
7z 7za
...
我可以实际执行的命令是7z:
>>> from subprocess import *
>>> Popen(['7z'], stdout=PIPE).communicate()
(b'\n7-Zip [64] 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18\np7zip Version 9.20 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,8 CPUs)\n
例如cd
是一个内置的shell命令,你在/bin
目录下找不到它,但在大多数“终端”(使用shell)中都能正常工作,因为它被构建到了你通常使用的shell中。
但是因为Python默认情况下不会在shell中执行命令,所以你必须依靠使用os.chdir(...)
或将你的命令包装在/ bin / sh -c“cd ...”
或类似内容中。
cd
不存在。 - Torxed