我试图将stdout中的参数与我拥有的已知字符串进行比较, 因此,如果两个字符串之间存在匹配,它将为我提供退出代码0 , 如果不匹配,则以退出代码1 结束。
我试图从函数输出中将stdout插入参数但是我收到错误。
这是我使用的代码:
import subprocess
from subprocess import check_output
def pwd():
pwdcmd = subprocess.call("pwd")
out = check_output([pwd()])
print "this is where you are --> " + out
从我读过的内容和尝试在命令上使用相同的命令而不是它运行的功能:
out = check_output(["pwd"])
print "this is where you are --> " + out
如何将标准输出放入"输出"来自函数的参数?
这是我得到的错误:
**
/opt/sign
Traceback (most recent call last):
File "/opt/sign/test.py", line 15, in <module>
out = check_output([pwd()])
File "/usr/lib64/python2.7/subprocess.py", line 568, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
AttributeError: 'NoneType' object has no attribute 'rfind'
Process finished with exit code 1
**
答案 0 :(得分:0)
目前还不清楚你在做什么。但这可行:
import subprocess
def pwd():
return subprocess.check_output(["pwd"])
out = pwd()
print "this is where you are --> " + out
简单:
import os
print "this is where you are --> " + os.getcwd()
第二种解决方案与平台无关,毫无疑问如何解码子进程调用在Python 3中为您提供的字节串。
答案 1 :(得分:0)
这是一种使用subprocess.Popen
而不是subprocess.call的方法,并从list of lists
而不是函数中读取命令。这应该可以满足您的需求:
import subprocess
# This list contains a list for each command, with list[0]
# being your desired output message, and list[1] being a list
# containing a command and its arguments.
command_list = [
["This is where you are -> ", ["pwd"]],
["Here's what lives above this place:\n", ["ls","-larth", ".."]]
]
# Here we iterate through the list.
for item in command_list:
# Execute your command using subprocess.Popen
with subprocess.Popen(item[1], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc:
# Assign its output to 'out'
out = proc.stdout.read()
# And print the message you have associated with the command,
# along with 'out', and any output from stdout andstderr
print(item[0], out)
print()
希望这会有所帮助。新年快乐!