gpt4 book ai didi

python - 我无法在子进程中从 os.system 获得相同的结果

转载 作者:太空宇宙 更新时间:2023-11-04 12:27:27 25 4
gpt4 key购买 nike

我想从 os.system 转换成子进程如下

os.system("egrep 'Invalid user' /home/bits/Desktop/Assessment/auth.log | cut -d ' ' -f 11 >tempfile.txt ") 

它有效,但是当我使用子进程编写相同的语句时,它会创建一个空文件,有人知道为什么以及如何解决这个问题吗?谢谢

a1=subprocess.Popen(["egrep \"Invalid users\" /home/bits/Desktop/Assessment/auth.log"],shell=True,stdout=subprocess.PIPE)   ### instead of /home/bits/Desktop/Assessment/auth.log please modify with your full path of auth.log
a2=subprocess.Popen(["cut -d \" \" -f 11 > /home/bits/Desktop/Assessment/rezolvare/tempfile.txt"],shell=True,stdin=a1.stdout,stdout=subprocess.PIPE)

最佳答案

您应该将输出文件作为 stdout 提供:

with open("/home/bits/Desktop/Assessment/rezolvare/tempfile.txt", "wb") as output:
a1 = subprocess.Popen(["egrep", "Invalid users", "/home/bits/Desktop/Assessment/auth.log"], stdout=subprocess.PIPE)
a2 = subprocess.Popen(["cut", "-d", " ", "-f", "11"], stdin=a1.stdout, stdout=output)

用纯 python 编写更简单:

with open("/home/bits/Desktop/Assessment/auth.log") as lines:
with open("/home/bits/Desktop/Assessment/rezolvare/tempfile.txt", "wb") as output:
for line in lines:
if "Invalid users" in line:
output.write(line.split(" ")[10] + "\n")

关于python - 我无法在子进程中从 os.system 获得相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44227045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com