我一直在使用Jupyter Notebook学习Principal Component Analysis from kaggle),但是当我运行此代码时
from subprocess import check_output
print(check_output(["ls", "../input"]).decode("utf8"))
我的错误低于
FileNotFoundError Traceback (most recent call last)
<ipython-input-3-de0e39ca3ab8> in <module>()
1 from subprocess import check_output
----> 2 print(check_output(["ls", "C:/Users/wanglei/Documents/input"]).decode("utf8"))
D:\Anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
624
625 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 626 **kwargs).stdout
627
628
D:\Anaconda3\lib\subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
691 kwargs['stdin'] = PIPE
692
--> 693 with Popen(*popenargs, **kwargs) as process:
694 try:
695 stdout, stderr = process.communicate(input, timeout=timeout)
D:\Anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds)
945 c2pread, c2pwrite,
946 errread, errwrite,
--> 947 restore_signals, start_new_session)
948 except:
949 # Cleanup if the child failed starting.
D:\Anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
1222 env,
1223 cwd,
-> 1224 startupinfo)
1225 finally:
1226 # Child is launched. Close the parent's copy of those pipe
路径是正确的,似乎来自子进程的所有调用都会失败。
有谁知道为什么会这样?
答案 0 :(得分:7)
此代码运行ls
command,is available on all POSIX-conforming systems。
您使用的是Microsoft Windows。默认情况下,Microsoft Windows不符合POSIX。例如,没有ls
二进制文件。因此,子流程无法找到文件ls
,因此会发出FileNotFoundError
。
您可以安装Microsoft's Bash on Windows,这将为您提供ls。
然而,列出目录的pythonic和更便携的方法不是首先使用子进程,而是内置os.listdir
:
import os
print(os.listdir('../input'))
答案 1 :(得分:0)
尝试通过添加cwd争论来指定工作目录,这应该可行
import os, subprocess
cwd = os.getcwd()
proc = subprocess.Popen(["ls" ,"../input"], cwd=cwd, stdout=subprocess.PIPE)
output = proc.stdout.read().decode("utf8")
答案 2 :(得分:0)
我碰巧有同样的问题。在Windows的Jupiter Notebook上,使用Phihag提供的以下代码对我很有用。谢谢。
import os
print(os.listdir('../input'))