简体   繁体   English

KeyError: 'print $2' when I use subprocess.call("ps -ef | grep wget | grep {0} | awk '{print $2}'

[英]KeyError: 'print $2' when I use subprocess.call("ps -ef | grep wget | grep {0} | awk '{print $2}'

In my macOS, I using a wget downloading the www.test.com index page.在我的 macOS 中,我使用 wget 下载www.test.com索引页面。

then I have below python code:然后我有下面的python代码:

#-*- coding:utf-8 -*-
import subprocess

url = "https://www.test.com"

subprocess.call("ps -ef | grep wget | grep {0}  | awk '{print $2}'".format(url), shell=True)

when I run it, I get issue:当我运行它时,出现问题:

subprocess.call("ps -ef | grep wget | grep {0}  | awk '{print $2}'".format(url), shell=True)
KeyError: 'print $2'

and I switch the subprocess.call() to os.system() , still get this issue.我切换subprocess.call()os.system()仍然得到这个问题。

Your error is not caused by subprocess, rather the string format.您的错误不是由子进程引起的,而是由字符串格式引起的。

"ps -ef | grep wget | grep {0}  | awk '{print $2}'".format(url)

you can use %s to forming string.您可以使用%s来形成字符串。

"ps -ef | grep wget | grep %s  | awk '{print $2}'"%(url)

You need to use subprocess.run()您需要使用subprocess.run()

From Docs来自文档

Code needing to capture stdout or stderr should use run() instead需要捕获 stdout 或 stderr 的代码应改用 run()

Note : Do not use stdout=PIPE or stderr=PIPE with this function.注意:不要将stdout=PIPEstderr=PIPE与此函数一起使用。 The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from.如果子进程生成足够的输出到管道以填充操作系统管道缓冲区,则子进程将阻塞,因为管道未被读取。

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

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