首页 > 解决方案 > 将命令从 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 .
}

标签: pythonshellmodulesh

解决方案


使用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 

推荐阅读