0

I would like to execute hello.py using test.sh. However, it seems test.sh read hello.py as sh file.

error message

line 1: syntax error near unexpected token `'hello''

test.sh

#!/user/bin/ python (which python path)
ARRAY=(1 2 3 4)
for num in ${ARRAY[@]}; do
    /artic/m-yasunaga/work/korin-3/src/example/hi.py
    echo $num"th loop"
done

hello.py

print('hello')

When I changed print('hello') to echo hello, it worked perfectly.

How can I execute hello.py as python code? ( I use linux )

4
  • Your python script needs a shebang line (see this question). Also, your shell script should have a shell shebang, not one referring to python (and it cannot contain parenthetical remarks, nor spaces in the middle of the path). The shebang line that starts a script indicates how to run that script, not others it may run. The file extension (like .sh or .py) is ignored when you run a script directly like this. Commented Apr 12, 2021 at 0:57
  • Actually, since your shell script uses an array (which is a bash extension, not available in all other shells), you should use a bash shebang (like #!/bin/bash or #!/usr/bin/env bash), not a generic shell shebang (like #!/bin/sh). Commented Apr 12, 2021 at 1:05
  • 2
    /user/bin/ python? That's ... bizarre. Try /usr/bin/python. Commented Apr 12, 2021 at 1:34
  • @JennyRowland : Adding to the comment given by Pursell, your Script is Shell, not Python. Trying to construct a #!-line for Python is even more bizarre.... Commented Apr 12, 2021 at 7:38

2 Answers 2

1

You have some syntax errors etc in your scripts.....try this:

Create the following two scripts.

Name: test.sh

#!/usr/bin/env bash
ARRAY=(1 2 3 4)
for num in ${ARRAY[@]}; do
    ./hello.py
    echo $num"th loop"
done

Name: hello.py

#!/usr/bin/env python
print('hello')

From your command line, run the following

chmod 700 test.sh ;  chmod 700 hello.py

Now from the command line, you can run:

./test.sh

The output will be:

>./test.sh 
hello
1th loop
hello
2th loop
hello
3th loop
hello
4th loop
Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't matter much here, but I'd also recommend double-quoting the variable references (for num in "${ARRAY[@]}"; do and echo "${num}th loop").
0

You should mention the python path

#!/user/bin/ python (which python path)

in hello.py file and make it executable using

chmod +x hello.py

Now you can use it as a executable.

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.