Ryan
Ryan

Reputation: 10099

running bash script from python file

I have a bash script which changes the path on my command line, This one,

#!/usr/bin/env python
cd /mnt/vvc/username/deployment/

I have a python script which i wish to run after the path changes to the desired path,

The script,

#!/usr/bin/env python
import subprocess
import os
subprocess.call(['/home/username/new_file.sh'])

for folder in os.listdir(''):
print ('deploy_predict'+' '+folder)

I get this

 File "/home/username/new_file.sh", line 2
 cd /mnt/vvc/username/deployment/
                                ^
SyntaxError: invalid syntax

Any suggestions on how can i fix this?thanks in advance

Upvotes: 0

Views: 195

Answers (1)

Daniel Centore
Daniel Centore

Reputation: 3349

You need to explicitly tell subprocess which shell to run the sh file with. Probably one of the following:

subprocess.call(['sh', '/home/username/new_file.sh'])
subprocess.call(['bash', '/home/username/new_file.sh'])

However, this will not change the python program's working directory as the command is run in a separate context.

You want to do this to change the python program's working directory as it runs:

os.chdir('/mnt/vvc/username/deployment/')

But that's not really great practice. Probably better to just pass the path into os.listdir, and not change working directories:

os.listdir('/mnt/vvc/username/deployment/')

Upvotes: 3

Related Questions