如果我用 Popen 调用它,为什么 NCat 会立即结束?
Why NCat overs immediately if I call it by Popen?
我必须在我的 python3-脚本中使用 NCat stdin-pipe,我决定为此使用 subprocess.Popen
。但即使我这样调用,NCat 也会立即结束并显示错误代码 2 并写道:Ncat: You must specify a host to connect to. QUITTING.
。我的代码:
import subsubprocess
a = subprocess.Popen(['nc', '--keep-open', '--listen', '8000'], stdin = subprocess.PIPE, shell = True)
...
我试着把 localhost
放在倒数第二个参数中:
a = subprocess.Popen(['nc', '--keep-open', '--listen', 'localhost', '8000'], stdin = subprocess.PIPE, shell = True)
但它给出了那个结果。在控制台中 nc --keep-open --listen 8000
和 nc --keep-open --listen localhost 8000
工作完美。我该怎么办?
这里的问题,我很确定,是我最近遇到的。当您传递参数列表并指定 shell = True
时,Popen
不会执行您期望的操作。当它们的使用相互排斥时是最快乐的。所以而不是:
a = subprocess.Popen(['nc', '--keep-open', '--listen', '8000'], stdin = subprocess.PIPE, shell = True)
我会做:
a = subprocess.Popen(['nc', '--keep-open', '--listen', '8000'], stdin = subprocess.PIPE)
或:
a = subprocess.Popen(['nc --keep-open --listen 8000'], stdin = subprocess.PIPE, shell = True)
我深入研究了文档,发现了一些有趣的花絮,这些花絮证实了我一直以来通过经验相信自己的直觉:
If shell is True, it is recommended to pass args as a string rather than as a sequence.
On POSIX with shell=True, the shell defaults to /bin/sh. ... If args
is a sequence, the first item specifies the command string, and any
additional items will be treated as additional arguments to the
shell itself.
所以我想额外的参数被提供给 /bin/sh
而不是你的 nc
。
我必须在我的 python3-脚本中使用 NCat stdin-pipe,我决定为此使用 subprocess.Popen
。但即使我这样调用,NCat 也会立即结束并显示错误代码 2 并写道:Ncat: You must specify a host to connect to. QUITTING.
。我的代码:
import subsubprocess
a = subprocess.Popen(['nc', '--keep-open', '--listen', '8000'], stdin = subprocess.PIPE, shell = True)
...
我试着把 localhost
放在倒数第二个参数中:
a = subprocess.Popen(['nc', '--keep-open', '--listen', 'localhost', '8000'], stdin = subprocess.PIPE, shell = True)
但它给出了那个结果。在控制台中 nc --keep-open --listen 8000
和 nc --keep-open --listen localhost 8000
工作完美。我该怎么办?
这里的问题,我很确定,是我最近遇到的。当您传递参数列表并指定 shell = True
时,Popen
不会执行您期望的操作。当它们的使用相互排斥时是最快乐的。所以而不是:
a = subprocess.Popen(['nc', '--keep-open', '--listen', '8000'], stdin = subprocess.PIPE, shell = True)
我会做:
a = subprocess.Popen(['nc', '--keep-open', '--listen', '8000'], stdin = subprocess.PIPE)
或:
a = subprocess.Popen(['nc --keep-open --listen 8000'], stdin = subprocess.PIPE, shell = True)
我深入研究了文档,发现了一些有趣的花絮,这些花絮证实了我一直以来通过经验相信自己的直觉:
If shell is True, it is recommended to pass args as a string rather than as a sequence.
On POSIX with shell=True, the shell defaults to /bin/sh. ... If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.
所以我想额外的参数被提供给 /bin/sh
而不是你的 nc
。