简体   繁体   English

从另一个目录运行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.... 我不知道这件事有些愚蠢,但是我今天尝试这样做,当它不起作用时感到很惊讶。

I have a directory C:\\test with a demo script, lets call it demo.py 我有一个带有演示脚本的目录C:\\test ,将其demo.py

  1. If i am in C:\\test then I can just do python demo.py . 如果我在C:\\test那么我可以做python demo.py Easy 简单
  2. I could also use a relative path, so from C:\\ , it's python test\\demo.py 我也可以使用相对路径,因此从C:\\出发,它是python test\\demo.py

What if C:\\test is on the path? 如果C:\\ test在路径上怎么办?

I was expecting to be able to now do python demo.py from anywhere however... 我希望现在能够从任何地方进行python demo.py ...

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

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? 从根本上来说,我是否对Python解释器如何找到要运行的脚本有误解? I don't think this is anything to do with PYTHONPATH, as I understood that to relate to loading of modules inside scripts. 我认为这与PYTHONPATH无关,因为我知道这与脚本中模块的加载有关。

This is on Windows 7, by the way. 顺便说一句,这是在Windows 7上。

The PATH is only used to search for commands. PATH仅用于搜索命令。 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 . 第一种方法是可以将Python脚本直接用作命令,在这种情况下,将使用PATH:只需使用demo.py而不是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. 在Windows上,可以给文件类型(由扩展名-.py赋予)来处理它们,而在类似Unix上,脚本的第一行可以声明将对其进行处理的程序。

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允许启动一个模块 ,该模块将通过使用python -m module或Windows py -m module在PYTHONPATH( 而不是 PATH)中进行搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM