How to call a shell script from python code?
The subprocess module will help you out.
Blatantly trivial example:
>>> import subprocess
>>> subprocess.call(['sh', './test.sh']) # Thanks @Jim Dennis for suggesting the []
0
>>>
Where test.sh
is a simple shell script and 0
is its return value for this run.
Run shell script from python
You should separate arguments:
call(['bash', 'run.sh'])
call(['ls','-l'])
Running bash script from within python
Making sleep.sh executable and adding shell=True
to the parameter list (as suggested in previous answers) works ok. Depending on the search path, you may also need to add ./
or some other appropriate path. (Ie, change "sleep.sh"
to "./sleep.sh"
.)
The shell=True
parameter is not needed (under a Posix system like Linux) if the first line of the bash script is a path to a shell; for example, #!/bin/bash
.
shell script execute python code as shell script
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
How to call a shell script function/variable from python?
No, that's not possible. You can execute a shell script, pass parameters on the command line, and it could print data out, which you could parse from Python.
But that's not really calling the function. That's still executing bash with options and getting a string back on stdio.
That might do what you want. But it's probably not the right way to do it. Bash can not do that many things that Python can not. Implement the function in Python instead.
Shell Script: Execute a python program from within a shell script
Just make sure the python executable is in your PATH environment variable then add in your script
python path/to/the/python_script.py
Details:
- In the file job.sh, put this
#!/bin/sh
python python_script.py
- Execute this command to make the script runnable for you :
chmod u+x job.sh
- Run it :
./job.sh
Call shell script from python code without any return value (0) or new lines
Just call it like this:
import subprocess
answer = subprocess.check_output('bash TestingCode', shell=True)
answer = answer.rstrip()
The reason is that your shell script is printing 19
followed by a new line. The return value from subprocess.check_output()
will therefore include the new line produced by the shell script. Calling str.rstrip()
will remove any trailing whitespace, leaving just '19'
in this case.
How do I execute a program or call a system command?
Use the subprocess
module in the standard library:
import subprocess
subprocess.run(["ls", "-l"])
The advantage of subprocess.run
over os.system
is that it is more flexible (you can get the stdout
, stderr
, the "real" status code, better error handling, etc...).
Even the documentation for os.system
recommends using subprocess
instead:
The
subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in thesubprocess
documentation for some helpful recipes.
On Python 3.4 and earlier, use subprocess.call
instead of .run
:
subprocess.call(["ls", "-l"])
How to call a python script on a new shell window from python code?
I would suggest using the subprocess
module (https://docs.python.org/2/library/subprocess.html).
In this way, you'll write something like the following:
import subprocess
cmd = ['gnome-terminal', '-x', 'bash', '-c']
for i in range(10):
name_of_file = "myscript"+str(i)+".py"
your_proc = subprocess.Popen(cmd + ['python %s' % (name_of_file)])
# or if you want to use the "modern" way of formatting string you can write
# your_proc = subprocess.Popen(cmd + ['python {}'.format(name_of_file)])
...
and you have more control over the processes you start.
If you want to keep using os.system()
, build your command string first, then pass it to the function. In your case would be:
cmd = 'gnome-terminal -x bash -c "python {}"'.format(name_of_file)
os.system(cmd)
something along these lines.
Thanks to @anishsane for some suggestions!
Calling a shell script from python
See my comment, best approach (i.m.o) would be to just use python only.
However, in answer of your question, try:
import sys
import subprocess
var="rW015005000000"
proc = subprocess.Popen(["/bin/bash", "/full/path/to/c.sh"], stdout=subprocess.PIPE)
# Best to always avoid shell=True because of security vulnerabilities.
proc.wait() # To make sure the shell script does not continue running indefinitely in the background
output, errors = proc.communicate()
print(output.decode())
# Since subprocess.communicate() returns a bytes-string, you can use .decode() to print the actual output as a string.
Related Topics
Complexity of *In* Operator in Python
How to Resolve Typeerror: Can Only Concatenate Str (Not "Int") to Str
Matplotlib Fill Between Multiple Lines
Does a File Object Automatically Close When Its Reference Count Hits Zero
Pylab.Ion() in Python 2, Matplotlib 1.1.1 and Updating of the Plot While the Program Runs
Split a String with Unknown Number of Spaces as Separator in Python
Which Is the Easiest Way to Simulate Keyboard and Mouse on Python
Sorting a List of Dot-Separated Numbers, Like Software Versions
How to Avoid Explicit 'Self' in Python
Naturally Sorting Pandas Dataframe
How to Create a "View" on a Python List