![](/img/trans.png)
[英]Why does python 3 tell me that there is no such file or directory when I use test.json in my code
[英]How do I run my Python script? Why does the command line tell me "no such file or directory"?
我在C:\Python27
安装了 Python 2.7 并且我添加了路径C:\Python27\;
到环境变量和.py:
到 PATHEXT。 我能够启动 Python。
我下载了一个文件夹google-python-exercises
到我的桌面,其中包含一个脚本hello.py
。
按照Google Developers course 中的建议,我尝试在命令提示符下使用python hello.py
运行脚本。
当我尝试这样做时,我收到消息: python: can't open file 'hello.py: [Errno 2] No such file or directory
。 出了什么问题,我该如何解决? 我发现我可以通过从文件夹中运行 cmd 来解决问题,但这似乎是一个临时解决方案。
在运行python之前,在命令行中输入cd
,它会告诉你当前所在的目录。python运行时,它只能访问该目录下的文件。 hello.py
需要在此目录中,因此您可以将hello.py
从其现有位置移动到此文件夹,就像移动 Windows 中的任何其他文件一样,或者您可以更改目录并在hello.py
所在的目录中运行 python。
编辑:除非提供了路径,否则 Python 无法访问子目录中的文件。 您可以通过提供路径访问任何目录中的文件。 python C:\\Python27\\Projects\\hello.p
我通过导航到 C:\\Python27\\Scripts 文件夹然后运行 file.py 文件而不是 C:\\Python27 文件夹解决了这个问题
根据您的问题,您正在运行 python2.7 和 Cygwin。
应该为 Windows 安装 Python,从您的问题来看似乎是这样。 如果“which python”打印出 /usr/bin/python ,那么从 bash 提示符您正在运行 cygwin 版本。
适当地设置 Python 环境变量,例如在我的情况下:
PY_HOME=C:\opt\Python27
PYTHONPATH=C:\opt\Python27;c:\opt\Python27\Lib
在这种情况下,运行 cygwin setup 并卸载所有 python。 之后运行“which pydoc”,如果它显示
/usr/bin/pydoc
将 /usr/bin/pydoc 替换为
#! /bin/bash
/cygdrive/c/WINDOWS/system32/cmd /c %PYTHONHOME%\Scripts\\pydoc.bat
然后将其添加到$PY_HOME/Scripts/pydoc.bat
rem wrapper for pydoc on Win32
@python c:\opt\Python27\Lib\pydoc.py %*
现在,当您输入 cygwin bash 提示符时,您应该看到:
$ pydoc
pydoc - the Python documentation tool
pydoc.py <name> ...
Show text documentation on something. <name>
may be the name of a Python keyword, topic,
function, module, or package, or a dotted
reference to a class or function within a
module or module in a package.
...
选项包括:
从hello.py
所在的文件夹运行命令(这样, hello.py
已经是文件的相对路径)。 这是OP找到的解决方案。
给出hello.py
文件的正确路径 - 绝对路径(例如C:/Users/me/Desktop/google-python-exercises/hello.py
)或相对路径(例如google-python-exercises/hello.py
,如果当前工作目录是桌面)。
将文件夹路径 ( C:/Users/me/Desktop/google-python-exercises
) 添加到PYTHONPATH
环境变量中,并将代码作为模块运行 ( python -m hello
)。
在所有情况下,都会直接给出路径 - Python 不会“搜索”文件。
尝试卸载 Python,然后重新安装,但这次请确保在安装过程中将选项 Add Python to Path 标记为已选中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.