python执行bat文件_使用python code运行.bat文件

1586010002-jmsa.png

I try to run a .bat file in Windows using Python script.

ask.bat file:

Application.exe work.xml

I write Python code :

import os

os.system("D:\xxx1\xxx2XMLnew\otr.bat ")

Output: when try to run the file its just give a blink of the command prompt, and the work is not performing.

Note: I try with alternate slash also , but it is not working.

And I also want to save output of the file in another file.

Can anyone suggest how can I make the script runnable.

解决方案import subprocess

filepath="D:/path/to/batch/myBatch.bat"

p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)

stdout, stderr = p.communicate()

print p.returncode # is 0 if success

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python执行外部的.bat文件可以通过`subprocess`模块来实现。`subprocess`模块允许你启动新的应用程序或进程,连接到它们的输入/输出/错误管道,并获取它们的返回码。以下是一个使用`subprocess`模块调用Windows批处理文件(.bat文件)的例子: ```python import subprocess # 指定.bat文件的路径 bat_file_path = 'C:\\path\\to\\your\\script.bat' # 使用subprocess.call来执行.bat文件 # 如果你需要传递参数给批处理文件,可以在这里添加 # 例如:subprocess.call([bat_file_path, 'arg1', 'arg2']) # 如果不需要返回值,则可以使用subprocess.run,它在Python 3.5及之后的版本中可用 result = subprocess.run([bat_file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 获取标准输出和标准错误输出 if result.stdout: print('Standard output:', result.stdout.decode()) if result.stderr: print('Standard error:', result.stderr.decode()) # 检查进程是否成功结束,其中result.returncode是进程的退出码 if result.returncode == 0: print('脚本执行成功') else: print('脚本执行失败,退出码:', result.returncode) ``` 注意替换`bat_file_path`变量中的路径为你自己的.bat文件的实际路径。如果你需要向批处理文件传递参数,可以直接在`subprocess.run`或`subprocess.call`函数的调用中添加参数列表。 确保你的Python环境有足够的权限去执行外部脚本,并且环境变量已经正确设置以识别`.bat`文件关联的程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值