检查套接字是否忙

时间:2019-04-10 18:14:27

标签: python subprocess python-sockets

我是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命令,就可以运行它。

我在这里错过了什么吗?还是有其他更好的方法可以做到这一点?如果是这样,请在这里帮助我了解问题。

谢谢。

3 个答案:

答案 0 :(得分: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 :(得分:1)

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

答案 2 :(得分:-1)

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

相关问题