Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to access data from an object that has just unpickled and use that with

os.popen()

hitting error

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'

or error:

ValueError: invalid mode 'htop' #my object value

using

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

or

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

code:

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""

My question is how do I use os.popen using my object data?

1 Answer

0 votes
by (36.8k points)

You need to create a string with command and argument

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

or you can use f-string

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

or if cmd and arg are strings

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

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

then use it as the first argument

os.popen(cmd) 

By the way, you can also create method __str__ in Zeroquery

class Zeroquery:

    # Initializer / Instance Attributes

    def __init__(self, cmd, arg):

        self.cmd = cmd

        self.arg = arg

    def __str__(self):

        return self.cmd + " " + self.arg

and then you can use str(t)

os.popen( str(t) )

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...