现在我正在运行一个
wsl
ubunutu 终端,并且在与主目录不同的目录中有一个 python script
。我可以让它像'ls'
一样运行单个命令,但我想cd
进入目录,然后在Ubuntu
上运行python脚本。
到目前为止,我已经使用了
subprocess.run
和 subprocess.popen
,它们都给了我同样的东西,返回 Ubuntu
的基本目录。
sub=subprocess.run(['wsl',"~","ls"],capture_output=True)
要更改目录并运行 Python 脚本,您可以使用 Python 中的 os 模块以及 subprocess.run。这是您的代码的修改版本: 导入子流程 导入操作系统
# Specify the path to your target directory
target_directory = '/path/to/your/target/directory'
# Change the working directory to the target directory
os.chdir(target_directory)
# Build the command to run your Python script
command = ['wsl', 'python', 'your_script.py']
# Run the command
subprocess.run(command, capture_output=True)