.bat文件:
@py C:\Users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\TestProgram(.bat batch file and shebang line usecase).py %*
@pause.py文件:
#! python3
print('Hello World, this is a test program for showing the use of .bat batch files, and the role of the shebang line.')当我在.bat或命令提示符中运行PowerShell文件时:
PS C:\Users\Universal Sysytem> py "C:\Users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\BatchFile-TestProgram.bat"
File "C:\Users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\BatchFile-TestProgram.bat", line 1
@py C:\Users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\TestProgram(.bat batch file and shebang line usecase).py %*
^
SyntaxError: invalid syntaxP.S.:
@py.exe而不是@py我如何解决这个问题?
发布于 2021-02-01 11:27:34
伙计们,我终于解决了!非常感谢各位,他们回答了我的问题,或者通过评论给出了反馈!我非常感谢你宝贵的时间来帮助像我这样的菜鸟。(谢谢!)
好吧,所以解决办法是:
首先,我对我的.bat文件/批处理文件做了一些修改。I在双引号(“)中封装了.py文件的路径。
@py "C:\Users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\TestProgram(.bat batch file and shebang line usecase).py"
@pause最后,不是在位置路径的开头运行具有py的.bat文件,而是运行.bat文件。在PowerShell中,移到.bat文件的目录中,然后运行.bat文件:
.\BatchFile-TestProgram.bat它返回正确的输出:
Hello World, this is a test program for showing the use of .bat batch files, and the role of the shebang line.
Press any key to continue . . .还可以从run Dialog (WIN + R)运行批处理文件。输出与直接在PowerShell中运行批处理文件相同。我刚刚输入了批处理文件的完整路径,并将其用双引号括起来:。
"c:\users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\BatchFile-TestProgram.bat"我学到的是:
py执行用Python编写的文件。它不执行.bat文件,因为Python解释器不理解写入.bat文件的CMD语法。发布于 2021-02-01 09:29:42
问题是
py "C:\...\BatchFile-TestProgram.bat"将尝试使用Python解释器运行.bat文件。这是一个错误,因为Python解释器理解Python语言,但不理解用.bat文件编写的/Powershell语言。
@py C:\Users\...已经是无效的Python语法了,因为@py被当作装饰器来处理,并且装饰器后面不能跟着像C这样的符号名。
如何解决这个问题:使用Powershell运行.bat文件(假设.bat文件本身是正确的),或者完全丢弃.bat文件,只需运行:
py "C:\Users\Universal Sysytem\Desktop\Python Scripts (Automate the Boring Stuff)\Automate the Boring Stuff with Python\TestProgram(.bat batch file and shebang line usecase).py"如果您希望您的Python代码暂停(如@pause),您可以在脚本末尾请求用户输入:
print("This is my script, hello!")
# run some code...
# wait for input, then exit
input("Press ENTER to exit...")发布于 2021-02-01 09:25:08
不要使用py标记,只需简单地将文件路径写到.bat文件:
C:\My\Path\To\stack.py
pause如果使用.bat文件运行此代码:
print("Hello")产出如下:
C:\My\Path\To\stack.py>C:\My\Path\To\stack.py\stack.py
Hello
C:\My\Path\To\stack.py>pause
Press any key to continue . . .https://stackoverflow.com/questions/65990074
复制相似问题