检查插座是否忙碌

问题描述 投票:3回答:3

我是Python中的Socket Programming的新手。我在Python 3.7中编写了以下代码:

trial socket list.朋友

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命令。

我在这里错过了什么吗?或者还有其他更好的方法吗?如果是的话,请帮助我理解这里的问题。

提前致谢。

python subprocess python-sockets
3个回答
1
投票

tnc是一个PowerShell 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

1
投票

尝试用Popen调用shell=True。以下是您的代码的外观:

import subprocess
import sys

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

command = "tnc " + HOST + " -PORT "
print(command)
process = subprocess.Popen(command, stdout=tempFile, shell=True)

Here是上市问题。


-1
投票

这里的问题是python脚本找不到tnc程序。程序根本没有安装,或者---如果已安装---它不在PATH变量中。

© www.soinside.com 2019 - 2024. All rights reserved.