[英]How to run batch command in my python script?
I have to run a one-line batch command in my Python script.我必须在我的 Python 脚本中运行一行批处理命令。
Currently, I am saving my command in a .bat
file and executing the .bat
file using the subprocess
.目前,我将命令保存在
.bat
文件中并使用subprocess
执行.bat
文件。 But I want to omit the .bat
file and directly include the command in my python
script.但我想省略
.bat
文件并直接将命令包含在我的python
脚本中。 Because I might need to use different bat files for different use cases.因为我可能需要针对不同的用例使用不同的 bat 文件。 I would prefer to use one dynamic python script than save multiple
.bat
files.我宁愿使用一个动态 python 脚本也不愿保存多个
.bat
文件。
bat command:蝙蝠命令:
"C:\Program Files (x86)\temp\FL.B5.exe" /s /a "C:\Users\kuk\Downloads\B5+Typ B.2.asc" /o "C:\Users\kuk\Download\B5+Typ B.2.docx"
Python script was: Python 脚本是:
import subprocess as sp
sp.call([r"C:\Users\kuk\Downloads\test.bat"])
What I want is:我想要的是:
import subprocess
exe = r"C:\Program Files (x86)\temp\FL.B5.exe"
input = r"C:\Users\kuk\Downloads\B5+Typ B.2.asc"
output = r"C:\Users\kuk\Downloads\B5+Typ B.2.docx"
cmd = '{} /s /a {} /o {}'.format(soft,var1,var2)
subprocess.call(cmd)
I don't know what is wrong, but unable to execute the script.我不知道出了什么问题,但无法执行脚本。
Any help would be appreciated!!任何帮助,将不胜感激!!
your question is ambiguous.你的问题是模棱两可的。 if i interpreted it correctly, you can use
os.system
如果我解释正确,你可以使用
os.system
os.system
is a function which executes commands from console. os.system
是一个 function,它从控制台执行命令。
import os
os.system('"C:\Program Files (x86)\temp\FL.B5.exe" /s /a "C:\Users\kuk\Downloads\B5+Typ B.2.asc" /o "C:\Users\kuk\Download\B5+Typ B.2.docx"')
Do not use input
as a variable name.不要使用
input
作为变量名。 It is a python built-in function.它是一个 python 内置 function。
The subprocess.call
method takes a list as an argument. subprocess.call
方法将一个列表作为参数。 When dealing with shell execution tasks I like to use the shlex
library to quote parameters and split commands into a list.在处理 shell 执行任务时,我喜欢使用
shlex
库来引用参数并将命令拆分为列表。
Note: I haven't had to execute scripts on Windows for about 12 years so I'm not sure how compatible shlex is with the platform.注意:我已经有 12 年没有在 Windows 上执行脚本了,所以我不确定 shlex 与该平台的兼容性如何。
import shlex
import subprocess as sp
exe = r"C:\Program Files (x86)\temp\FL.B5.exe"
in_file = r"C:\Users\kuk\Downloads\B5+Typ B.2.asc"
out_file = r"C:\Users\kuk\Downloads\B5+Typ B.2.docx"
params = tuple([shlex.quote(p) for p in (exe, in_file, out_file)])
command = f'%s /s /a %s /o %s' % params
sp.call(shlex.split(command))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.