![](/img/trans.png)
[英]how to generalize/get base directory for Linux path for python script
[英]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.