python - 将命令从 python 文件传递到 shell 脚本(Linux)
问题描述
我编辑了这篇文章,以便我可以提供有关我正在努力实现的目标的更多信息。基本上我希望能够在一个目录中打开 VSCode,我可以通过我创建的 shell 命令在我正在运行的 python 文件中输入该目录。所以我需要的是 python 文件询问我要打开的文件夹的名称,将该信息传递给终端,以便它可以 cd 进入该文件夹并自动打开 vscode。我尝试使用 os.system() ,正如我所读到的,这是我可以实现该目标的方法之一。问题是,如果我使用像 os.system('date') 或 os.system('code') 这样的标准命令,它可以毫无问题地工作。如果我尝试使用 os.system(cd /directory/) 没有任何反应。正如建议的那样,我也尝试过,subprocess.call(["cd", "/home/simon/Desktop"])
但终端给了我错误:FileNotFoundError: [Errno 2] No such file or directory: 'cd'
我将包含两个 python 文件:
import os, subprocess
PATH = "/home/simon/Linux_Storage/Projects"
def main():
print("\n")
print("********************")
for folder in os.listdir(PATH):
print(folder)
print("********************")
project = input("Choose project: ")
print("\n")
folders = os.listdir(PATH)
while project:
if project in folders:
break
else:
print("Project doesn't exist.")
project = input("Choose project: ")
os.system(f"cd /home/simon/Linux_Storage/Projects/{project}")
if __name__ == "__main__":
main()
和shell脚本(也许我应该在这里改变一些东西):
function open() {
python3 .open.py
code .
}
解决方案
使用os.chdir()
代替os.system('cd /home/simon/Desktop')
#change directory
os.chdir('/home/simon/Desktop')
#get current path
os.getcwd()
#execute script
exec(open('path/to/yourfile.py').read())
#then change the path back to the current working directory
推荐阅读
- bootstrap-4 - 隐藏标题导航
- xamarin.forms - Xamarin Forms(Android):ListView向上滑动以取消拉动以刷新
- python - 对视图的请求总是在 Django 中异步运行
- c - pthread/uthread 类型变量
- node.js - Node.js 绝对路径和相对路径导致 2 个单独的引用,还是它们相同?
- nltk - 名称“nltk”未定义
- java - Visual Studio Code Spring Boot 重新加载静态内容
- java - 通过使用 UPPERCASE 或 LOWERCASE 释放的 JTextField 键在 SQL 表中搜索
- c# - 控制台应用程序和异步等待示例被阻塞
- machine-learning - “NoneType”对象没有属性“add_summary”