Issue
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
Solution
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.
Answered By - tdelaney Answer Checked By - Cary Denson (WPSolving Admin)