python3 error: invalid mode %r" % mode, trying to use object in os.popen

python3 error: invalid mode %r" % mode, trying to use object in os.popen

我正在尝试从一个刚刚解封的对象中访问数据并将其与

一起使用
os.popen()

点击错误

Traceback (most recent call last):
  File "tmpclient4.py", line 46, in <module>
    stream = os.popen('%t.cmd', '%t.arg')
  File "/usr/lib/python3.8/os.py", line 978, in popen
    raise ValueError("invalid mode %r" % mode)
ValueError: invalid mode '%t.arg'

或错误:

ValueError: invalid mode 'htop' #my object value

使用

stream = os.popen('%t.cmd', '%t.arg')

stream = os.popen(t.cmd, t.arg)

代码:

import socket
import pickle
import os

HEADERSIZE = 10

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.42.14', 666))

class Zeroquery:
        # Initializer / Instance Attributes
        def __init__(self, cmd, arg):
                self.cmd = cmd
                self.arg = arg
while True:
        full_msg = b''
        new_msg = True
        while True:
                msg = s.recv(16)
                if new_msg:
                        print("new msg len:",msg[:HEADERSIZE])
                        msglen = int(msg[:HEADERSIZE])
                        new_msg = False

                print(f"full message length: {msglen}")

                full_msg += msg


                print(len(full_msg))

                if len(full_msg)-HEADERSIZE == msglen:
                        print("full msg recvd")
                        t = pickle.loads(full_msg[HEADERSIZE:])
                        print(t.cmd, t.arg)
                        if t.cmd:
                                stream = os.popen(t.cmd, t.arg)
                                output = stream.read()
                                print(output)
                        new_msg = True
                        full_msg = b""

如何使用我的对象数据 os.popen?

您必须使用命令和参数创建字符串

cmd = "{} {}".format(t.cmd, t.arg)

或使用 f-string

cmd = f"{t.cmd} {t.arg}"

如果cmdarg是字符串那么你可以

cmd = " ".join([t.cmd, t.arg])

cmd = t.cmd + " " + t.arg

现在您可以将它用作第一个参数

os.popen(cmd)

编辑:

最终您可以在 Zeroquery

中创建方法 __str__
class Zeroquery:
    # Initializer / Instance Attributes
    def __init__(self, cmd, arg):
        self.cmd = cmd
        self.arg = arg

    def __str__(self):
        return self.cmd + " " + self.arg

然后你可以使用str(t)

os.popen( str(t) )

顺便说一句:

Zeroquery__str__ 那么你可以打印它(即使没有 str()

print( t )

print() 将使用此 __str__ 转换为字符串。