0

I am writing a program where I am giving a small part:-

#!/usr/bin/env python
import os
import subprocess

whoami = subprocess.check_output("whoami", shell=True)
print whoami
os.chdir("/")
os.chdir("/home/"+whoami+"/Silly")
pwd = subprocess.check_output("pwd", shell=True)
print pwd

After executing the program I got this:-

/usr/bin/python2.7 /home/rocky/PycharmProjects/Silly/Tester2.py
rocky
Traceback (most recent call last):

File "/home/rocky/PycharmProjects/Silly/Tester2.py", line 8, in 
<module>
os.chdir("/home/"+whoami+"/Silly")
OSError: [Errno 2] No such file or directory: '/home/rocky\n/Silly'

Process finished with exit code 1

Using PyCharm by JetBrains on Linux. When ever I take the username I get the "\n" with the user name. I tried using

whoami = whoami[:-2]

But failed.

1 Answers1

0

The reason your code is not working is because whoami is a byte stream with a '\n' at the end.

use strip() to remove '\n' from whoami object.

And convert it to string by decoding it in utf-8.

whoami = whoami.strip().decode("utf-8")
Vikash Singh
  • 13,213
  • 8
  • 40
  • 70