-1

Currently, I am using a python script to run commands in Linux shell. When I change the directory it doesn't seem to work (when I ran the command ls it listed files of the initial directory). I want to change the directory to the desktop. My Code:

import os
os.popen("cd Desktop")
d = os.popen("ls")
x = d.read()
print (x)
oz123
  • 27,559
  • 27
  • 125
  • 187
  • Try [`os.chdir()`](https://docs.python.org/3.3/library/os.html#os.chdir) – Filip Młynarski Jan 30 '19 at 17:39
  • Each time you execute `os.popen()` it is running the specified command in another process. So it does not affect your python process. Think of it as opening a terminal window and typing the command, then closing that window. The next `os.popen()` is not affected by the previous one. – John Anderson Jan 30 '19 at 17:44
  • `d = os.popen("cd Desktop && ls")` or `d = os.popen("ls ./Desktop")` – Maurice Meyer Jan 30 '19 at 17:58
  • Possible duplicate of [How do I change directory (cd) in Python?](https://stackoverflow.com/q/431684/608639), [How to change the working directory for a shell script](https://unix.stackexchange.com/q/42617/56041) on [Unix & Linux Stack Exchange](http://unix.stackexchange.com/), etc. – jww Jan 31 '19 at 00:22

2 Answers2

1

It's much better to use the subprocess module. It has a nicer API and does accept a keyword for this:

>>> import subprocess as sp
>>> sp.call("ls -ll", cwd='/tmp', shell=True)
oz123
  • 27,559
  • 27
  • 125
  • 187
  • Though maybe avoid the `shell=True` too. You'll need to split the command into a list yourself then `sp.call(['ls', '-ll'], cwd='/tmp')` -- see also https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess ... and while we are at it, probably prefer `check_call` or `subprocess.run(..., check=True)` (see https://stackoverflow.com/questions/4256107/running-bash-commands-in-python/51950538#51950538) – tripleee Jan 30 '19 at 18:41
0

The easiest and probably the simplest solution is to do here is to use os.chdir. Below is an example

In[6]: os.listdir()
Out[6]: 
['.flask-env',
 'mydb_app',
'requirements.txt',
 '.idea',
 'sample_file_auth.py',
 'login_app']
In[7]: os.chdir('/home/rbhanot/tools')
In[8]: os.listdir()
Out[8]: ['miniconda3', 'nvim']
Rohit
  • 3,659
  • 3
  • 35
  • 57