gpt4 book ai didi

python - 检查套接字是否忙

转载 作者:行者123 更新时间:2023-11-28 18:01:14 25 4
gpt4 key购买 nike

我是 Python 套接字编程的新手。我在 Python 3.7 中编写了以下代码:

trialSocketList.py

import subprocess
import sys

HOST = sys.argv[1]
PORT = sys.argv[2]

command = "tnc " + HOST + " -PORT "
print(command)
subprocess.call(command + PORT)

我在 Windows CMD 中传递以下内容:

python trialSocketList.py "127.0.0.1" 445

但是我在执行上面的代码时遇到了以下错误:

tnc 127.0.0.1 -PORT
Traceback (most recent call last):
File "trialSocketList.py", line 14, in <module>
subprocess.call(command + PORT)
File "C:\Python37\lib\subprocess.py", line 323, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Python37\lib\subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "C:\Python37\lib\subprocess.py", line 1178, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

当我在同一代码中尝试使用 netstat -an 而不是命令 tnc 127.0.0.1 -PORT 时,代码运行完美。上面几行代码是我看完后写的this API。

*如果我在 Windows cmd 中直接点击它,我可以运行 tnc 命令。

我是不是漏掉了什么?或者还有其他更好的方法吗?如果是这样,那么请帮助我理解这里的问题。

提前致谢。

最佳答案

tncPowerShell command .您需要像这样使用 PowerShell 显式运行它:

import subprocess
import sys

HOST = "127.0.0.1"
PORT = 445
command = "tnc " + HOST + " -PORT " + str(PORT)
print(command)
subprocess.call(["powershell.exe",command],stdout=sys.stdout)

输出:

tnc 127.0.0.1 -PORT 445

ComputerName : 127.0.0.1
RemoteAddress : 127.0.0.1
RemotePort : 445
InterfaceAlias : Loopback Pseudo-Interface 1
SourceAddress : 127.0.0.1
TcpTestSucceeded : True

关于python - 检查套接字是否忙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55618923/

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