繁体   English   中英

如何在python脚本中更改Linux的目录?

[英]How to change the directory of Linux in python script?

目前,我正在使用 python 脚本在 Linux shell 中运行命令。 当我更改目录时,它似乎不起作用(当我运行命令ls它列出了初始目录的文件)。 我想将目录更改为桌面。 我的代码:

import os
os.popen("cd Desktop")
d = os.popen("ls")
x = d.read()
print (x)

使用subprocess模块要好得多。 它有一个更好的 API,并接受一个关键字:

>>> import subprocess as sp
>>> sp.call("ls -ll", cwd='/tmp', shell=True)

最简单也可能是最简单的解决方案是使用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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM