当前,我正在使用python脚本在Linux shell中运行命令。当我更改目录时,它似乎不起作用(当我运行命令ls
时,它列出了初始目录的文件)。我想将目录更改为桌面。
我的代码:
import os
os.popen("cd Desktop")
d = os.popen("ls")
x = d.read()
print (x)
答案 0 :(得分:0)
最好使用subprocess
模块。它具有更好的API,并且确实为此接受关键字:
>>> import subprocess as sp
>>> sp.call("ls -ll", cwd='/tmp', shell=True)
答案 1 :(得分:0)
在这里要做的最简单,可能也是最简单的解决方案是使用os.chdir
。下面是一个示例
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']