Windows 命令行和 Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/981691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:37:54  来源:igfitidea点击:

windows command line and Python

pythonwindowscommand-line

提问by Tyler

I have a python script that i want to run from the command line but unsure how to run it. Thanks :)

我有一个 python 脚本,我想从命令行运行它,但不确定如何运行它。谢谢 :)

回答by SilentGhost

I do it this way:

我这样做:

C:\path\to\folder> yourscript.py

回答by Joey

python myscript.py

python myscript.py

回答by gimel

See Basic Hints for Windows Command Line Programming.

请参阅Windows 命令行编程的基本提示

If your python installation directory is included in %PATH%-

如果您的python安装目录包含在%PATH%-

C:\> python myscript.py

If you know the installation path:

如果你知道安装路径:

C:\> C:\python26\python myscript.py

And, you can insert a hashbangin the 1st line of the script:

并且,您可以hashbang在脚本的第一行插入一个:

#! C:\python26\python

and it will run by typing just the script name. This is the content of p.py:

它将通过键入脚本名称来运行。这是内容p.py

#!C:\python26\python
import sys
print sys.path

And calling it directly from a cmd.exewindow:

并直接从cmd.exe窗口调用它:

C:\>p.py
['C:\WINDOWS\system32\python26.zip', 'C:\Python26\DLLs',
'C:\Python26\lib', 'C:\Python26\lib\plat-win',
'C:\Python26', 'C:\Python26\lib\site-packages', 
'C:\Python26\lib\site-packages\win32', 'C:\Python26\lib]

回答by David Cournapeau

If your script is foo.py, you can simply do

如果你的脚本是 foo.py,你可以简单地做

C:\Python25\python.exe foo.py

Assuming you have python 2.5 installed in the default location. Alternatively, you can add C:\Python25 to your %PATH%, so that:

假设您在默认位置安装了 python 2.5。或者,您可以将 C:\Python25 添加到您的 %PATH%,以便:

python foo.py

will work. But be aware that changing %PATH% may affect applications (that's why it is not done by the python installer by default).

将工作。但请注意,更改 %PATH% 可能会影响应用程序(这就是默认情况下 python 安装程序不这样做的原因)。

回答by Andy

You might find it useful to include a .bat file which calls the .py script. Then all you need to do is to type the name of your script to run it.

您可能会发现包含一个调用 .py 脚本的 .bat 文件很有用。然后您需要做的就是输入脚本的名称来运行它。

Try something like: python %~dp0\%~n0.py %*

尝试类似:python %~dp0\%~n0.py %*

(From http://wiki.tcl.tk/2455)

(来自http://wiki.tcl.tk/2455

回答by Anurag Uniyal

  1. do you have python installed? if not install it from python.org
  2. on command line use

    python "path to script.py"

  3. if python is not in PATH list you can add it to PATH in environment variables or directly use path to python.exe e.g.

        c:\python25\python.exe myscript.py
    
  1. 你有安装python吗?如果不是从 python.org 安装它
  2. 在命令行使用

    python“脚本.py的路径”

  3. 如果 python 不在 PATH 列表中,您可以将其添加到环境变量中的 PATH 或直接使用 python.exe 的路径,例如

        c:\python25\python.exe myscript.py