0

I am trying to create a python script script.py in bash and importing a bash script.

#!/usr/bin/env python    
import os
import glob
from fnmatch import fnmatch
# importing a software
python_package = os.system("""#!/path_to_bin/bin/python \
from __future__ import print_function, division \
from python_toolbox.toolbox.some_toolbox import run \
if __name__ == '__main__': \
    run()"""

# testing 
greeting = "Hello world!"
print(greeting)

Running the script.py in python3

$python3 script.py
  File "script.py", line 15
    greeting = "Hello world!"
SyntaxError: invalid syntax
4
  • 1
    This is python running python... no bash. Commented Nov 8, 2022 at 3:07
  • Thanks @tdelaney, why there is a syntax error then? Commented Nov 8, 2022 at 3:08
  • 1
    Um... os.system(... has no closing paren. It's best to read your own code before asking others to read it for you. Commented Nov 8, 2022 at 3:09
  • 2
    You are missing a paren at the end of your os.system(... call. Python figured that out on the next line. Commented Nov 8, 2022 at 3:10

1 Answer 1

1

Nominally the problem is that you are missing the closing paren on the os.system call. But there is a better way to run a python program than trying to write it all on the command line. Instead, you can pass a full script, including newlines, to python's stdin.

#!/usr/bin/env python    
import sys
import subprocess as subp

# importing a software
def run_script():
    subp.run([sys.executable, "-"], input=b"""
print("I am a called python script")
""")

# testing
run_script() 
greeting = "Hello world!"
print(greeting)

In this script, the second python script is run whenever you call run_script. Notice that the script in the string has to follow the normal python indendation rules. So, there is indentation inside run_script but then the string holding the second script starts its indentation all the way to the left again.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much @tdelaney. How do I call the software later in the code? I assigned the software into a variable like this: variable = subp.run([sys.executable, "-"], input=b""" print("I am a called python script") """). But seems doesn't work.
That ran the script and saved run 's return value to variable. Instead you could write a function. I updated the example to do that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.