为Python脚本创建BAT文件

发布于 2024-10-10 01:19:44 字数 58 浏览 0 评论 0原文

如何创建一个简单的 BAT 文件来运行位于 C:\somescript.py 的 python 脚本?

How can I create a simple BAT file that will run my python script located at C:\somescript.py?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

这是语法:
“python.exe path”“python script path”pause

"C:\Users\hp\AppData\Local\Programs\Python\Python37\python.exe" "D:\TS_V1\TS_V2.py"
pause

基本上会发生什么,屏幕会出现几秒钟,然后消失,注意这两件事:

  1. 在将文件保存为bat文件时,将扩展名保存为txt文件文件而不是所有文件和编码 ANSI
  2. 如果程序仍然无法运行,请将批处理文件和 python 脚本保存在同一文件夹中,并在环境变量中指定该文件夹的路径。

This is the syntax:
"python.exe path""python script path"pause

"C:\Users\hp\AppData\Local\Programs\Python\Python37\python.exe" "D:\TS_V1\TS_V2.py"
pause

Basically what will be happening the screen will appear for seconds and then go off take care of these 2 things:

  1. While saving the file you give extension as bat file but save it as a txt file and not all files and Encoding ANSI
  2. If the program still doesn't run save the batch file and the python script in same folder and specify the path of this folder in Environment Variables.
睫毛溺水了 2024-10-17 01:19:45

如果这是与当前目录不同的目录中的 BAT 文件,您可能会看到类似“python: can't open file 'somescript.py': [Errno 2] No such file or directory”的错误。可以通过使用 %~dp0 指定 BAT 文件的绝对路径(驱动器号和路径)来解决此问题批处理文件)。

@echo off
python %~dp0\somescript.py %*

(这样您就可以忽略 c:\ 或其他内容,因为也许您可能想要移动此脚本)

If this is a BAT file in a different directory than the current directory, you may see an error like "python: can't open file 'somescript.py': [Errno 2] No such file or directory". This can be fixed by specifying an absolute path to the BAT file using %~dp0 (the drive letter and path of that batch file).

@echo off
python %~dp0\somescript.py %*

(This way you can ignore the c:\ or whatever, because perhaps you may want to move this script)

兲鉂ぱ嘚淚 2024-10-17 01:19:45

使用任何文本编辑器并将以下代码保存为 runit.bat

@echo off
title Execute Python [NarendraDwivedi.Org]
:main
echo.
set/p filename=File Name :
echo. 
%filename%
goto main

现在将此文件放入 python 脚本所在的文件夹中。运行此文件并输入 python 脚本的文件名以使用批处理文件(cmd)运行 python 程序

参考:Narendra Dwivedi - 如何使用批处理文件运行 Python

Use any text editor and save the following code as runit.bat

@echo off
title Execute Python [NarendraDwivedi.Org]
:main
echo.
set/p filename=File Name :
echo. 
%filename%
goto main

Now place this file in the folder where python script is present. Run this file and enter python script's file name to run python program using batch file (cmd)

Reference : Narendra Dwivedi - How To Run Python Using Batch File

或十年 2024-10-17 01:19:45

创建一个空文件并将其命名为“run.bat”

在我的例子中,我使用“py”,因为它更方便,请尝试:

C:
cd C:\Users\user\Downloads\python_script_path
py your_script.py

Create an empty file and name it "run.bat"

In my case i use "py" because it's more convenient, try:

C:
cd C:\Users\user\Downloads\python_script_path
py your_script.py
給妳壹絲溫柔 2024-10-17 01:19:45
@echo off
call C:\Users\[user]\Anaconda3\condabin\conda activate base
"C:\Users\[user]\Anaconda3\python.exe" "C:\folder\[script].py"
@echo off
call C:\Users\[user]\Anaconda3\condabin\conda activate base
"C:\Users\[user]\Anaconda3\python.exe" "C:\folder\[script].py"
还不是爱你 2024-10-17 01:19:45
ECHO OFF
set SCRIPT_DRIVE = %1
set SCRIPT_DIRECTORY = %2
%SCRIPT_DRIVE%
cd %SCRIPT_DRIVE%%SCRIPT_DIRECTORY%
python yourscript.py`
ECHO OFF
set SCRIPT_DRIVE = %1
set SCRIPT_DIRECTORY = %2
%SCRIPT_DRIVE%
cd %SCRIPT_DRIVE%%SCRIPT_DIRECTORY%
python yourscript.py`
终陌 2024-10-17 01:19:45

我这样做了并且有效:
我的项目位于 D: 中,我的批处理文件位于桌面中,如果您将其放在同一驱动器中,只需忽略第一行并在第二行中更改 de D 目录,

在第二行中更改文件的文件夹,将 将你的文件夹

中第三行的文件名更改为

D:
cd D:\python_proyects\example_folder\
python example_file.py

i did this and works:
i have my project in D: and my batch file is in the desktop, if u have it in the same drive just ignore the first line and change de D directory in the second line

in the second line change the folder of the file, put your folder

in the third line change the name of the file

D:
cd D:\python_proyects\example_folder\
python example_file.py

醉梦枕江山 2024-10-17 01:19:45

暂时将 python 添加到系统 PATH 可能会有所帮助:

rem path to the Python installation folder
set Python=F:\python311

rem add Python path to environment path
set PATH=%Python%;%PATH%

rem run the Python script
python C:\somescript.py

Adding python to system PATH temporarily may help:

rem path to the Python installation folder
set Python=F:\python311

rem add Python path to environment path
set PATH=%Python%;%PATH%

rem run the Python script
python C:\somescript.py
忆梦 2024-10-17 01:19:45

start xxx.py

您可以将其用于其他一些文件类型。

start xxx.py

You can use this for some other file types.

寄风 2024-10-17 01:19:44
c:\python27\python.exe c:\somescript.py %*
c:\python27\python.exe c:\somescript.py %*
菩提树下叶撕阳。 2024-10-17 01:19:44

打开命令行(⊞ Win+Rcmd↵ Enter
然后输入python -V↵ Enter

您应该会收到响应,例如 Python 2.7.1

如果不这样做,则可能没有安装 Python。首先解决这个问题。

一旦你有了Python,你的批处理文件应该看起来像这样。

@echo off
python c:\somescript.py %*
pause

这将使命令窗口在脚本完成后保持打开状态,以便你可以看到任何错误或消息。一旦您对此感到满意,您可以删除“暂停”行,命令窗口将在完成后自动关闭。

Open a command line (⊞ Win+R, cmd, ↵ Enter)
and type python -V, ↵ Enter.

You should get a response back, something like Python 2.7.1.

If you do not, you may not have Python installed. Fix this first.

Once you have Python, your batch file should look like

@echo off
python c:\somescript.py %*
pause

This will keep the command window open after the script finishes, so you can see any errors or messages. Once you are happy with it you can remove the 'pause' line and the command window will close automatically when finished.

善良天后 2024-10-17 01:19:44

以下是如何将批处理代码和 python 代码放入单个文件中:

0<0# : ^
''' 
@echo off
echo batch code
python "%~f0" %*
exit /b 0
'''

print("python code")

''' 分别开始和结束 python 多行注释。

0<0# : ^ 更有趣 - 由于批处理中的重定向优先级,它会被批处理脚本解释为 :0<0# ^,批处理脚本是一个标签,执行不会显示在屏幕上。末尾的插入符号将转义新行,第二行将附加到第一行。对于 python,它将是 0<0 语句和内联注释的开头。

功劳归于 siberia-man

Here's how you can put both batch code and the python one in single file:

0<0# : ^
''' 
@echo off
echo batch code
python "%~f0" %*
exit /b 0
'''

print("python code")

the ''' respectively starts and ends python multi line comments.

0<0# : ^ is more interesting - due to redirection priority in batch it will be interpreted like :0<0# ^ by the batch script which is a label which execution will be not displayed on the screen. The caret at the end will escape the new line and second line will be attached to the first line.For python it will be 0<0 statement and a start of inline comment.

The credit goes to siberia-man

在风中等你 2024-10-17 01:19:44

只需在 python 脚本的同一文件夹中打开一个包含这两行的批处理文件:

somescript.py
pause

Just simply open a batch file that contains this two lines in the same folder of your python script:

somescript.py
pause
蒲公英的约定 2024-10-17 01:19:44

您可以直接在批处理文件中使用python代码,
https://gist.github.com/jadient/9849314

@echo off & python -x "%~f0" %* & goto :eof
import sys
print("Hello World!")

请参阅解释,Python 命令行 -x 选项

You can use python code directly in batch file,
https://gist.github.com/jadient/9849314.

@echo off & python -x "%~f0" %* & goto :eof
import sys
print("Hello World!")

See explanation, Python command line -x option.

我是有多爱你 2024-10-17 01:19:44

如果您已将 Python 添加到您的 PATH 中,那么您也可以像这样简单地运行它。

python somescript.py

If you've added Python to your PATH then you can also simply run it like this.

python somescript.py
清泪尽 2024-10-17 01:19:44

--- xxx.bat ---

@echo off
set NAME1="Marc"
set NAME2="Travis"
py -u "CheckFile.py" %NAME1% %NAME2%
echo %ERRORLEVEL%
pause

--- yyy.py ---

import sys
import os
def names(f1,f2):

    print (f1)
    print (f2)
    res= True
    if f1 == "Travis":
         res= False
    return res

if __name__ == "__main__":
     a = sys.argv[1]
     b = sys.argv[2]
     c = names(a, b) 
     if c:
        sys.exit(1)
    else:
        sys.exit(0)        

--- xxx.bat ---

@echo off
set NAME1="Marc"
set NAME2="Travis"
py -u "CheckFile.py" %NAME1% %NAME2%
echo %ERRORLEVEL%
pause

--- yyy.py ---

import sys
import os
def names(f1,f2):

    print (f1)
    print (f2)
    res= True
    if f1 == "Travis":
         res= False
    return res

if __name__ == "__main__":
     a = sys.argv[1]
     b = sys.argv[2]
     c = names(a, b) 
     if c:
        sys.exit(1)
    else:
        sys.exit(0)        
白云悠悠 2024-10-17 01:19:44

与 npocmaka 的解决方案类似,如果除了 python 代码之外,批处理文件中还有不止一行批处理代码,请查看以下内容:http://lallouslab.net/2017/06/12/batchography-embedding-python-scripts-in-your- batch-file-script/

@echo off
rem = """
echo some batch commands
echo another batch command
python -x "%~f0" %*
echo some more batch commands
goto :eof

"""
# Anything here is interpreted by Python
import platform
import sys
print("Hello world from Python %s!\n" % platform.python_version())
print("The passed arguments are: %s" % sys.argv[1:])

这段代码的作用是通过将所有批处理代码放入多行字符串中,将自身作为 python 文件运行。该字符串的开头位于名为 rem 的变量中,以使批处理代码将其作为注释读取。由于 -x 参数,包含 @echo off 的第一行在 Python 代码中被忽略。

值得一提的是,如果您想在批处理代码中使用 \,例如在文件路径中,则必须使用 r"""...""" 将其包围起来,将其用作没有转义序列的原始字符串。

@echo off
rem = r"""
...
"""

Similar to npocmaka's solution, if you are having more than one line of batch code in your batch file besides the python code, check this out: http://lallouslab.net/2017/06/12/batchography-embedding-python-scripts-in-your-batch-file-script/

@echo off
rem = """
echo some batch commands
echo another batch command
python -x "%~f0" %*
echo some more batch commands
goto :eof

"""
# Anything here is interpreted by Python
import platform
import sys
print("Hello world from Python %s!\n" % platform.python_version())
print("The passed arguments are: %s" % sys.argv[1:])

What this code does is it runs itself as a python file by putting all the batch code into a multiline string. The beginning of this string is in a variable called rem, to make the batch code read it as a comment. The first line containing @echo off is ignored in the python code because of the -x parameter.

it is important to mention that if you want to use \ in your batch code, for example in a file path, you'll have to use r"""...""" to surround it to use it as a raw string without escape sequences.

@echo off
rem = r"""
...
"""
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文