Вопрос

I need to change directory (CD) to a Linux user's Desktop. Now, the Linux username is a variable, so I tried having the path, but of course it wont work:

import os
os.chdir("/path/to/dir")

So I tried the following:

   subprocess.call("cd", "~/Desktop")
   subprocess.call("pwd")

But I got the following error:

Traceback (most recent call last):
  File "SIPHON.py", line 132, in <module>
    subprocess.call("cd", "~/Desktop")
  File "/usr/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 658, in __init__
    raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer

How can I cd to a user's desktop in Linux, using Python?

Thanks in advance.

Это было полезно?

Решение

You need to expand ~ as actual path using os.path.expanduser:

>>> os.path.expanduser('~/Desktop')
'/home/falsetru/Desktop'

os.chdir(os.path.expanduser('~/Desktop'))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top