简体   繁体   中英

How to run cmd commands from python?

I am having problems with running some cmd commands from python script. Found lot of examples and stuff explaining subprocess.run but can't get my scripts running...

I have batch script with commands like:

set PATH=%PATH%;"C:\d\program\program_4\bin"
set PROGRAM_WAS_RUNNING=0

echo Starting PROGRAM (headless)
programd --file "C:\d\projects\project1\tool\program.exe" --dont-breakaway-from-job
if %ERRORLEVEL%==0 goto next0
    echo -- PROGRAM with GUI is running
    set PROGRAM_WAS_RUNNING=1

:next0

.. etc

Tried with this code but won't work:

command = subprocess.run(["set", "PATH=%PATH%;C:\d\program\program_4\bin"])
command = subprocess.run(["set", "PROGRAM_WAS_RUNNING=0"])

Can someone please give an example and explain in short what would be the best way to translate all of these and other similar batch commands into Python? Thanks,

It's Simple

    import os
    os.system("your commands here")

Notepad Example:

>>> import os
>>> os.system("notepad.exe")
0
>>> 

It's import to study 'os' module. It provides some functions to facilitate the interface with Operating System like

os.putenv(key, value)
os.getenv(key, default=None)
os.uname()
os.system(command)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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