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)
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)
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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.