如何使用子进程函数执行命令?

问题描述 投票:0回答:1

我想在一个python脚本中执行这些命令。

  1. 以管理员身份打开cmd
  2. cd C:\elastic_stack\logstash-7.6.2
  3. .\bin\logstash -f C:/Users/Asus/Desktop/flask_project_part2/project/logstash_file.conf

这就是我想做的,但它不执行最后的配置文件。

import os, subprocess 
from subprocess import *  
os.chdir("C:\\Users") 
cmd = subprocess.Popen(["runas", "/noprofile", "/user:Administrator", "|", "cd", "C:/elastic_stack/logstash-7.6.2"], shell=True)        
cmd.subprocess.run(["./bin/logstash", "-f", "C:/Users/Asus/Desktop/flask_project_part2/project/logstash_file.conf"], shell=True)
python subprocess
1个回答
0
投票

你有一个前进和后退斜杠的组合,但我假设你已经在windows机器上安装了ELK。

不幸的是,我没有机会使用windows机器 所以我没有机会测试这些代码。但主要应该是这样的。

import os
import subprocess

# desired path
target_dir = os.path.join("C:",os.sep,"elastic_stack",os.sep,"logstash-7.6.2")

# small check
if os.path.isdir(target_dir):
  os.chdir(target_dir)
else:
  print(" pathname does not refer to an existing directory")

# current working directory
print(os.getcwd())

# start logstash directly os.system will return the return code of the command if it's 0 means OK
os.system(".\\bin\\logstash -f C:\\Users\\Asus\\Desktop\\flask_project_part2\\project\\logstash_file.conf")

# if you need the output after you started logstash it will work ONLY in Python3

process = subprocess.run([".\\bin\\logstash", "-f", "C:\\Users\\Asus\\Desktop\\flask_project_part2\\project\\logstash_file.conf"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)


output = process.stdout
errors = process.stderr

PS: 你可以 os.sep 因为这样一来,分离器就与系统无关了。

shell 参数默认设置为 False 而这意味着没有启动系统shell,而且如果 shell=True 意味着系统外壳将首先旋转起来。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.