抱歉,如果标题有点困惑;我不确定如何表达它。我是一名正在学习语言学类(class)的初学者,在将一些脚本传输到命令提示符时遇到了一些问题。我正在使用 Windows 8.1 和 python 3.6.0,如果有帮助的话。
我遇到的问题是我可以在 python.exe 程序中编写一个脚本,它会完全按照它应该的方式工作。然后我将使用命令提示符运行完全相同的脚本,它唯一返回的是一个空行。
例如,我可以手动将其输入 python 控制台并获得正确的输出:
>>>print("hello")
hello
但如果我将它保存在 Notepad++ 文件中并使用命令提示符执行相同的脚本,它会看起来像这样(请原谅我的屠宰路径娱乐):
C:\Users\username\Python>hello.py
C:\Users\username\Python>
“hello.py”是我尝试使用我在 Python 控制台中手动输入的完全相同的代码运行的脚本,但是当我尝试打开该文件时,它什么也没做。
虽然我尝试运行的每个脚本都不会发生这种情况,但我无法弄清楚是什么触发了这种情况发生。我没有收到任何错误,所以我不知道如何进行反复试验。这使得在我添加元素时检查我的工作变得越来越困难,而且我不确定如何解决这个问题。如果有人有任何建议,我将不胜感激。
请您参考如下方法:
仅使用脚本名称从 Windows 命令行运行 Python 脚本
配置 Windows 文件关联指针
Set the python.exe full explicit path as in the below #3 for the correct value where this is on your system
- 以管理员身份打开提升的 [cmd.exe] 命令提示符
- 输入
ASSOC .py=PythonScript并按 Enter - 输入
FTYPE PythonScript="C:\Program Files\Python\python.exe""%1"%*并按 Enter - 输入
SET PATHEXT=.py;%PATHEXT%并按 Enter
仅使用脚本名称从 Shell 执行
如果您确实需要从命令行运行脚本而不告诉 shell python 脚本文件的完整显式路径,那么您需要将此脚本所在的路径添加到 %PATH%环境变量。
- 以管理员身份打开提升的 [cmd.exe] 命令提示符
- 键入
SET PATH=%PATH%;C:\Program Files\Python其中C:\Program Files\Python是您系统上存在的值。
现在,您只需键入带有或不带有文件扩展名的脚本名称,而无需执行 CD 到另一个目录或显式指定 python 脚本的完整路径。
更多资源
FTYPE/?Displays or modifies file types used in file extension associations FTYPE [fileType[=[openCommandString]]] fileType Specifies the file type to examine or change openCommandString Specifies the open command to use when launching files of this type. Type FTYPE without parameters to display the current file types that have open command strings defined. FTYPE is invoked with just a file type, it displays the current open command string for that file type. Specify nothing for the open command string and the FTYPE command will delete the open command string for the file type. Within an open command string %0 or %1 are substituted with the file name being launched through the assocation. %* gets all the parameters and %2 gets the 1st parameter, %3 the second, etc. %~n gets all the remaining parameters starting with the nth parameter, where n may be between 2 and 9, inclusive. For example: ASSOC .pl=PerlScript FTYPE PerlScript=perl.exe %1 %* would allow you to invoke a Perl script as follows: script.pl 1 2 3 If you want to eliminate the need to type the extensions, then do the following: set PATHEXT=.pl;%PATHEXT% and the script could be invoked as follows: script 1 2 3ASSOC/?Displays or modifies file extension associations ASSOC [.ext[=[fileType]]] .ext Specifies the file extension to associate the file type with fileType Specifies the file type to associate with the file extension Type ASSOC without parameters to display the current file associations. If ASSOC is invoked with just a file extension, it displays the current file association for that file extension. Specify nothing for the file type and the command will delete the association for the file extension.
