简体   繁体   English

为 python 脚本创建 BAT 文件

[英]Creating a BAT file for python script

How can I create a simple BAT file that will run my python script located at C:\somescript.py?如何创建一个简单的 BAT 文件来运行位于 C:\somescript.py 的 python 脚本?

c:\python27\python.exe c:\somescript.py %*

Open a command line ( ⊞ Win + R , cmd , ↵ Enter ) and type python -V , ↵ Enter .打开命令行( ⊞ Win + R , cmd , ↵ Enter )并输入python -V , ↵ Enter

You should get a response back, something like Python 2.7.1 .您应该得到回复,类似于Python 2.7.1

If you do not, you may not have Python installed.如果没有,您可能没有安装 Python。 Fix this first.先解决这个问题。

Once you have Python, your batch file should look like一旦你有了 Python,你的批处理文件应该看起来像

@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.一旦您对它感到满意,您可以删除“暂停”行,完成后命令窗口将自动关闭。

Here's how you can put both batch code and the python one in single file:以下是将批处理代码和 python 代码放在单个文件中的方法:

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

print("python code")

the ''' respectively starts and ends python multi line comments. '''分别开始和结束 python 多行注释。

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

The credit goes to siberia-man归功于西伯利亚人

Just simply open a batch file that contains this two lines in the same folder of your python script:只需在 python 脚本的同一文件夹中打开一个包含这两行的批处理文件:

somescript.py
pause

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

python somescript.py

You can use python code directly in batch file, https://gist.github.com/jadient/9849314 .您可以直接在批处理文件中使用 python 代码, 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 .请参阅说明, Python 命令行 -x 选项

--- xxx.bat --- --- xxx.bat ---

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

--- yyy.py --- --- 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)        

This is the syntax: "python.exe path""python script path"pause这是语法:“python.exe 路径”“python 脚本路径”暂停

"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在保存文件时,您将扩展名设为 bat 文件,但将其保存为 txt 文件,而不是所有文件和编码 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.如果程序仍然不运行,请将批处理文件和 python 脚本保存在同一文件夹中,并在环境变量中指定该文件夹的路径。

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".如果这是与当前目录不同的目录中的 BAT 文件,您可能会看到类似“python: 无法打开文件 'somescript.py': [Errno 2] 没有这样的文件或目录”这样的错误。 This can be fixed by specifying an absolute path to the BAT file using %~dp0 (the drive letter and path of that batch file ).这可以通过使用%~dp0 (该批处理文件驱动器号和路径)指定 BAT 文件的绝对路径来解决。

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

(This way you can ignore the c:\\ or whatever, because perhaps you may want to move this script) (这样你就可以忽略c:\\或其他什么,因为你可能想移动这个脚本)

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/与 npocmaka 的解决方案类似,如果您的批处理文件中除了 python 代码之外还有不止一行批处理代码,请查看: http : //lallouslab.net/2017/06/12/batchography-embedding-python-scripts -在你的批处理文件脚本/

@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.这段代码的作用是将所有批处理代码放入一个多行字符串中,将自己作为一个 python 文件运行。 The beginning of this string is in a variable called rem, to make the batch code read it as a comment.该字符串的开头在一个名为 rem 的变量中,以使批处理代码将其作为注释读取。 The first line containing @echo off is ignored in the python code because of the -x parameter.由于-x参数,包含@echo off的第一行在 python 代码中被忽略。

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

@echo off
rem = r"""
...
"""
ECHO OFF
set SCRIPT_DRIVE = %1
set SCRIPT_DIRECTORY = %2
%SCRIPT_DRIVE%
cd %SCRIPT_DRIVE%%SCRIPT_DIRECTORY%
python yourscript.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我这样做并有效:我在 D: 中有我的项目,我的批处理文件在桌面上,如果你有它在同一个驱动器中,只需忽略第一行并更改第二行中的 de D 目录

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

Use any text editor and save the following code as runit.bat使用任何文本编辑器并将以下代码另存为 runit.bat

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

Create an empty file and name it "run.bat"创建一个空文件并将其命名为“run.bat”

In my case i use "py" because it's more convenient, try:就我而言,我使用“py”因为它更方便,请尝试:

C:
cd C:\Users\user\Downloads\python_script_path
py your_script.py
@echo off
call C:\Users\[user]\Anaconda3\condabin\conda activate base
"C:\Users\[user]\Anaconda3\python.exe" "C:\folder\[script].py"

start xxx.py开始 xxx.py

You can use this for some other file types.您可以将其用于其他一些文件类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM