我想向subprocess.communicate输入一个参数,但它总是超出我的期望。文件夹树:
├── file1
├── file2
├── main.pyMain.py的内容:
import subprocess
child = subprocess.Popen(["ls"], stdin=subprocess.PIPE, universal_newlines=True)
filepath = '/Users/haofly'
child.communicate(filepath)无论我将文件路径更改为什么,结果都只列出当前文件夹(file1、file2、main.py)。
我是不是误解了沟通?我是怎么把数据发送到Popen的?
如果我想发送密码,那么ssh命令如何?
subprocess.Popen(['ssh', 'root@ip'], stdin=subprocess.PIPE, universal_newlines=True)
发布于 2017-05-22 13:22:08
您不能将数据“管道”到ls --它基于提供的CLI参数列出目录--但如果您不希望将文件夹作为参数传递给ls,则应该能够使用xargs来实现您想要的结果(实质上是将您的文件夹作为参数传递给ls):
import subprocess
child = subprocess.Popen(["xargs", "ls"], stdin=subprocess.PIPE, universal_newlines=True)
filepath = '/Users/haofly'
child.communicate(filepath)发布于 2017-05-22 13:13:49
我认为您在Popen调用中缺少了一个shell参数:
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode‘'ls’可能不是说明这一概念的最佳命令,但如果您想将参数传递给命令,则必须执行类似的操作:
cmd = ['cmd', 'opt1', 'optN']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
out, err = p.communicate('args')
print out发布于 2017-05-22 13:14:47
手动使用ls时,是否只键入ls,按Enter,然后键入文件路径以响应提示符?这就是您在这里尝试使用它的方法-- .communicate()的参数成为子进程的标准输入,实际上ls完全忽略了这个标准输入。它希望将目录列表为命令行参数,您可以将其指定为["ls", filepath]。
https://stackoverflow.com/questions/44113296
复制相似问题