1

I'm trying to run sh-script from python file

my_script.sh

#!/usr/bin/python

rm category.xml 

python file

import subprocess
subprocess.call(["../my_script.sh"])

And I get

    File "../my_scrypt.sh", line 3
    rm category.xml
              ^
SyntaxError: invalid syntax

How to fix this?

4 Answers 4

4

You used a shebang line of #!/usr/bin/python on a file that isn't Python. Change the shebang line.

Better yet, don't call out to shell scripts when you can call Python functions to do the same thing:

import os
os.remove("category.xml")
Sign up to request clarification or add additional context in comments.

2 Comments

I have a shebang line, my_script.sh #!/usr/bin/python rm category.xml
Yes: it's wrong: you are saying to run the file with Python. It's not Python.
1

Look at your shell code. You using python interpreter #!/usr/bin/python and feeding it with bash commands rm category.xml.

Fixed shell script:

#!/bin/bash

rm category.xml 

2 Comments

bash and sh has difference. However, it needs to be #!/bin/sh
It depends on code, i think rm is just for testing. sh does not support many useful features of bash, but it is portable. As for me, i've never faced any problems with bash on the modern linux systems and only benefit from advanced syntax.
0

if you're using python 2x

use commands module:

import commands
print commands.getoutput('sh my_script.sh')

if using python 3x

use subprocess module:

import subprocess
print(subprocess.getoutput('sh my_script.sh'))

1 Comment

subprocess has been available since Python 2.4, and commands was deprecated in Python 2.6 (honestly, I'd never heard of it until now).
0

Try this,

my_script.sh

#!/usr/bin/sh

rm category.xml

Trivial approach:

>>> import subprocess
>>> subprocess.call(['./my_script.sh']) 
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.