使用Jupyter notebook时运行此段代码:
from subprocess import check_output
print(check_output(["ls", "C:/Kaggle/Titanic/input"]).decode("utf8"))
出现错误:
FileNotFoundError Traceback (most recent call last)
<ipython-input-10-cf7fc002cdae> in <module>()
32 # input directory
33 from subprocess import check_output
---> 34 print(check_output(["ls", "C:/Kaggle/Titanic/input"]).decode("utf8"))
35 #import os
36 #print(os.listdir('C:/Kaggle/Titanic/input'))
~\Anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
374
375 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 376 **kwargs).stdout
377
378
~\Anaconda3\lib\subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
451 kwargs['stderr'] = PIPE
452
--> 453 with Popen(*popenargs, **kwargs) as process:
454 try:
455 stdout, stderr = process.communicate(input, timeout=timeout)
~\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, encoding, errors, text)
754 c2pread, c2pwrite,
755 errread, errwrite,
--> 756 restore_signals, start_new_session)
757 except:
758 # Cleanup if the child failed starting.
~\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)
1153 env,
1154 os.fspath(cwd) if cwd is not None else None,
-> 1155 startupinfo)
1156 finally:
1157 # Child is launched. Close the parent's copy of those pipe
FileNotFoundError: [WinError 2] 系统找不到指定的文件。
- 原因
因为使用的是Windows,默认情况下,Windows不符合POSIX。例如,没有ls二进制文件。因此,子进程无法找到该文件ls,从而发出一个FileNotFoundError。
- 解决办法
- 可以在Windows上安装微软的Bash,它会给你ls。
- 列出目录更简单的方法是使用os.listdir:
import os
print(os.listdir('C:/Kaggle/Titanic/input'))
结果展示:[‘gender_submission.csv’, ‘test.csv’, ‘train.csv’]
注:摘自stackoverflow