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 )

Jenny I
  • 91
  • 1
  • 2
  • 7
  • Your python script needs a shebang line (see [this question](https://stackoverflow.com/questions/6908143/should-i-put-shebang-in-python-scripts-and-what-form-should-it-take)). 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. – Gordon Davisson Apr 12 '21 at 00: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`). – Gordon Davisson Apr 12 '21 at 01:05
  • 2
    `/user/bin/ python`? That's ... bizarre. Try `/usr/bin/python`. – William Pursell Apr 12 '21 at 01: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.... – user1934428 Apr 12 '21 at 07:38

2 Answers2

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
Dharman
  • 30,962
  • 25
  • 85
  • 135
linuxnut
  • 58
  • 5
  • 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"`). – Gordon Davisson Apr 12 '21 at 04:30
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.

DARK_C0D3R
  • 2,075
  • 16
  • 21