简体   繁体   English

如何从 python 运行 cmd 命令?

[英]How to run cmd commands from python?

I am having problems with running some cmd commands from python script.我在从 python 脚本运行一些 cmd 命令时遇到问题。 Found lot of examples and stuff explaining subprocess.run but can't get my scripts running...找到了很多解释 subprocess.run 的示例和内容,但无法让我的脚本运行......

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 .. 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?有人可以举个例子并简短地解释将所有这些和其他类似批处理命令转换为 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.学习“os”模块很重要。 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)

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

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