0
import os
ot = os.popen("%s") %"ls"
TypeError: unsupported operand type(s) for %: 'file' and 'str'

I can not figure it out why error occurs. I mean it's pure string operation, right? Any help could be appreciated.

3
  • 2
    Did you mean os.popen("%s" % "ls")? What you've got now tries to apply % to the result of os.popen("%s") (hence ‘'file'’ in the error) and "ls" (‘'str'’). And what has this got to do with Bash?! Commented May 22, 2016 at 15:39
  • is ls the file name or the command you want to execute in bash and get results here ? Commented May 22, 2016 at 15:43
  • You are right, the % str should be touched after "%s" , can not be separated or comes error... Commented May 22, 2016 at 16:12

1 Answer 1

6

Python is great because of the interactive shell.

Try:

>>> import os
>>> os.popen("%s")
<open file '%s', mode 'r' at 0x10d020390>

You can see the error in front of you. The result of os.popen is a file. You are then applying a string operation to that.

Translating what you have to what I think you are trying to do, try:

>>> os.popen("%s" % "ls").read()

Or, directly:

>>> os.popen("ls").read()

But the subprocess module is usually preferred:

>>> import subprocess
>>> subprocess.check_output("ls")
Sign up to request clarification or add additional context in comments.

3 Comments

Oh...Yes, I mixed up... Thanks very much...haha
@PuMing.Z: or just os.listdir().
@J.F.Sebastian: Yes. that's a better choice. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.