连续写入多个命令到 WSL ubuntu 终端

问题描述 投票:0回答:1

现在我正在运行一个

wsl
ubunutu 终端,并且在与主目录不同的目录中有一个
python script
。我可以让它像
'ls'
一样运行单个命令,但我想
cd
进入目录,然后在
Ubuntu
上运行python脚本。

到目前为止,我已经使用了

subprocess.run
subprocess.popen
,它们都给了我同样的东西,返回
Ubuntu
的基本目录。

sub=subprocess.run(['wsl',"~","ls"],capture_output=True)
python subprocess ubuntu-16.04 wsl-2
1个回答
0
投票

要更改目录并运行 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)
  1. os.chdir(target_directory):这会更改当前的工作 目录到指定的target_directory。
  2. ['wsl', 'python','your_script.py']:这是在 WSL 中运行 Python 脚本的命令。
© www.soinside.com 2019 - 2024. All rights reserved.