簡體   English   中英

檢查插座是否忙碌

[英]Check if a socket is busy or not

我是Python中的Socket Programming的新手。 我在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時,代碼完美地運行。 我在閱讀 API后編寫了以上幾行代碼。

* 如果我直接在Windows cmd中點擊它,我可以運行tnc命令。

我在這里錯過了什么嗎? 或者還有其他更好的方法嗎? 如果是的話,請幫助我理解這里的問題。

提前致謝。

嘗試使用shell=True調用Popen 以下是您的代碼的外觀:

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)

是列出的問題。

tnc是一個PowerShell命令 您需要使用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腳本找不到tnc程序。 程序根本沒有安裝,或者---如果已安裝---它不在PATH變量中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM