从另一个目录运行 python 脚本 [英] Run python script from another directory
问题描述
我不知道这一点我觉得有点愚蠢,但我今天尝试这样做,但当它不起作用时感到惊讶......
I feel a little foolish that I don't know this, but I tried to do it today and was surprised when it didn't work....
我有一个带有演示脚本的目录 C:\test
,我们称之为 demo.py
I have a directory C:\test
with a demo script, lets call it demo.py
- 如果我在
C:\test
中,那么我可以只做python demo.py
.简单 - 我也可以使用相对路径,所以从
C:\
开始,它是python test\demo.py
- If i am in
C:\test
then I can just dopython demo.py
. Easy - I could also use a relative path, so from
C:\
, it'spython test\demo.py
如果 C:\test 在路径上怎么办?
我希望现在能够从任何地方执行 python demo.py
但是...
I was expecting to be able to now do python demo.py
from anywhere however...
python: can't open file 'demo.py': [Errno 2] No such file or directory
我觉得自己很愚蠢,因为我认为这很简单,但我四处搜索并没有找到解决方案.我是否从根本上误解了 Python 解释器如何找到要运行的脚本?我不认为这与 PYTHONPATH 有任何关系,因为我理解这与在脚本中加载模块有关.
I feel foolish because I thought this was straightforward, but I have searched around and have not found a solution. Am I fundamentally misunderstanding something here about how the Python interpreter finds scripts to run? I don't think this is anything to do with PYTHONPATH, as I understood that to relate to loading of modules inside scripts.
顺便说一下,这是在 Windows 7 上.
This is on Windows 7, by the way.
推荐答案
PATH 仅用于搜索命令.第一种方法是 Python 脚本可以直接用作命令,在这种情况下将使用 PATH:只需使用 demo.py
而不是 pythondemo.py
.
The PATH is only used to search for commands. A first way is that a Python script can be used directly as a command and in that case the PATH will be used: just use demo.py
instead of python demo.py
.
它将依赖于操作系统特定的方式.在 Windows 上,文件类型(由扩展名 - 这里是 .py 给出)可以被赋予默认的应用程序来处理它们,而在类 Unix 上,脚本的第一行可以声明将处理它的程序.
It will rely on OS specific ways. On Windows, file type (given by the extension - here .py) can be given default application to process them, while on Unix-like, the first line of a script can declare the program that will process it.
或者,python 允许使用 python -m module
启动将在 PYTHONPATH(not PATH)中搜索的 module 或对于 Windows py -m 模块
.
Alternatively, python allows to launch a module that will be searched in the PYTHONPATH (not PATH) by using python -m module
or for Windows py -m module
.
这篇关于从另一个目录运行 python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!