Home > Back-end >  How to run batch command in my python script?
How to run batch command in my python script?

Time:11-22

I have to run a one-line batch command in my Python script.

Currently, I am saving my command in a .bat file and executing the .bat file using the subprocess. But I want to omit the .bat file and directly include the command in my python script. Because I might need to use different bat files for different use cases. I would prefer to use one dynamic python script than save multiple .bat files.

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:

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!!

CodePudding user response:

The subprocess.call method takes a list as an argument. When dealing with shell execution tasks I like to use the shlex library to quote parameters and split commands into a list.

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.

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))

CodePudding user response:

your question is ambiguous. if i interpreted it correctly, you can use os.system

os.system is a function which executes commands from console.

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. It is a python built-in function.

  • Related