无法从批处理文件执行Python脚本

时间:2017-03-14 13:51:14

标签: python windows batch-file command

我试图从命令行运行Python程序,所以我创建了一个批处理文件,如下所示:

@py.exe C:\MyPythonScripts\program.py%*
@pause

脚本应该打印一条简单的消息,但是当我输入" program"在Windows运行程序中,cmd会出现一秒钟并自行关闭。我做错了什么?。

这是代码:

#!python3

def printPicnic(itemsDict,leftWidth,rightWidth):
    print('PICNIC ITEMS'.center(leftWidth + rightWidth,'-'))
    for k,v in itemsDict.items():
        print(k.ljust(leftWidth,'.') + str(v).rjust(rightWidth))

picnicItems = {'sandwiches':4, 'apples': 12, 'cups': 4, 'cookies':8000}
printPicnic(picnicItems,12,5)
printPicnic(picnicItems,20,6)

这是我的PATH变量:

> C:\Program Files (x86)\Common
> Files\Intel\Shared
> Files\cpp\bin\Intel64;C:\ProgramData\Oracle\Java\javapath;C:\Program
> Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files
> (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS
> Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program
> Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program
> Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files
> (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files
> (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files
> (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files
> (x86)\AMD\ATI.ACE\Core-Static;C:\Program Files
> (x86)\Skype\Phone\;C:\Program
> Files\Java\jdk1.8.0_121\bin;C:\MyPythonScripts;C:\Python34;C:\Program
> Files (x86)\Common Files\Intel\Shared
> Files\cpp\bin\Intel64;C:\ProgramData\Oracle\Java\javapath;C:\Program
> Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files
> (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS
> Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program
> Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program
> Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files
> (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files
> (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files
> (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files
> (x86)\AMD\ATI.ACE\Core-Static;C:\Program Files
> (x86)\Skype\Phone\;C:\Program
> Files\Java\jdk1.8.0_121\bin;C:\Python34\Scripts

3 个答案:

答案 0 :(得分:3)

关于批处理文件,我建议您执行以下更改:

您在path%*之间错过了一个空格,并在引号中包含path,以防止打破时出现空格路径

@echo off
py.exe "C:\MyPythonScripts\program.py" %1 %2 %3 %4 %5 %6 %7 %8 %9
pause

答案 1 :(得分:2)

批处理文件中的问题是缺少 SPACE

@rem               THERE MUST BE A SPACE:
@rem                                 |
@rem                                 V
@py.exe C:\MyPythonScripts\program.py %*
@pause

此外,我强烈建议在路径周围加上引号,以避免白色空格和其他空间字符出现问题。

答案 2 :(得分:0)

您可以使用以下方法执行此操作:

@ECHO OFF
setlocal
set PYTHONPATH=C:\Python35 (you version of python)
C:\MyPythonScripts\program.py  %1<-- (you you have arg)  
endlocal