Write multiple commands in a row to WSL ubuntu terminal

86 views Asked by At

Right now I am running a wsl ubunutu terminal and have a python script in a directory that is different to the home directory. I can get it to run a single command to it like 'ls' but i want to cd in to the directory and then run the python script on Ubuntu.

So far I have used subprocess.run as well as subprocess.popen and both of them have gotten me the same thing which returns the base directory of of Ubuntu.

sub=subprocess.run(['wsl',"~","ls"],capture_output=True)
1

There are 1 answers

0
julianofischer On

To change the directory and run the Python script, you can make use of the os module in Python along with subprocess.run. Here's a modified version of your code: import subprocess import os

# 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): This changes the current working directory to the specified target_directory.
  2. ['wsl', 'python','your_script.py']: This is the command to run your Python script in WSL.