0

I have this function to get a file type :

def get_file_type():
try:
    cmd = ['/usr/bin/file', '/home/user']
    p = Popen(cmd, stdout=PIPE).communicate()[0]
    p = str(p).split(':')[1:]
    if len(p) > 1:
        ' : '.join(p).strip().replace('\\n', '')
    else:
        p = p[0].strip().replace('\\n', '')
    print(p)
except CalledProcessError:
    print('unknown')

But it returns this : directory' The ending apostrophe is not a typo, it is what bothers me. And I don't understand why (not that it bothers me.. ;) )

Thank you

4
  • 1
    Impossible to reproduce. What is the value of p prior to the reassignment? Commented Sep 14, 2017 at 13:49
  • 1
    When len(p) > 1, you are performing a join, strip, and replace that you are throwing away the result of. You presumably want to assign that back to p. Commented Sep 14, 2017 at 13:52
  • @tobias_k p before reassignment : [" directory\\n'"] Commented Sep 14, 2017 at 13:59
  • @jasonharper yes ^^ thanks Commented Sep 14, 2017 at 13:59

1 Answer 1

3

The problem is that you're treating bytes as a string and you're using Python3. So what you're getting when you call str(p) looks like this:

"b'/home/user: directory\\n'"

You could fix this by doing p.decode().split instead of str(p).split

Sign up to request clarification or add additional context in comments.

1 Comment

I'm currently upgrading to python3, I thought it was the right way to bytes to string : I know now it isn't. Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.