从另一个目录运行python脚本

时间:2018-12-19 10:40:05

标签: python windows

我不知道这一点有点愚蠢,但是我今天尝试这样做,当它不起作用时感到很惊讶。...

我有一个带有演示脚本的目录C:\test,我们叫它demo.py

  1. 如果我在C:\test中,那么我可以做python demo.py。容易
  2. 我也可以使用相对路径,所以从C:\开始,它是python test\demo.py

如果C:\ test 在路径上怎么办?

我希望现在可以从任何地方进行python demo.py,但是...

python: can't open file 'demo.py': [Errno 2] No such file or directory

我觉得很愚蠢,因为我这很简单,但是我四处寻找并且没有找到解决方案。从根本上来说,我是否对Python解释器如何找到要运行的脚本有误解?我认为这与PYTHONPATH无关,因为我知道这与脚本中模块的加载有关。

顺便说一下,这是在Windows 7上。

1 个答案:

答案 0 :(得分:0)

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.

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.

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.