Running shell commands within python interpreter [duplicate] - python

This question already has answers here:
How do I execute a program or call a system command?
(65 answers)
Closed 8 years ago.
Is there a simple method for calling shell command line arguments (like ls or pwd) from within python interpreter?

In plain python, you need to use something along the lines of this:
from subprocess import check_output
check_output("ls", shell=True)
In IPython, you can run either of those commands or a general shell command by starting off with !. For example
! echo "Hello, world!" > /tmp/Hello.txt
If you're using python interactively, you would almost certainly be happier with IPython.

If you meant to use the Python shell interactively while being able to call commands (ls, pwd, ...) check out iPython.

Related

How do we create alias from python program/script? [duplicate]

This question already has an answer here:
create unix alias using a python3 script
(1 answer)
Closed 2 years ago.
I want to create an alias' through python program. I intend to use python as a replacement for shell scripting.
What I tried is:
import os
os.system('alias go2dir="cd /i/want/to/goto/this/dir"')
...and it does not work. I know the reason - that system command 'alias...' is getting executed in another shell and not in the current one where this python script is executed. So, that alias is not available to this shell.
What I don't know is - (In general,) how do we execute a command from a python program in the same shell where this python program is being executed. So that (in this case) the alias is available till the shell terminal is open?
The way other applications that want to automate actions in the user's shell work is that they write shell commands to their standard output. Then you can execute them with eval.
makealias.py:
print('alias go2dir="cd /i/want/to/goto/this/dir"')
Then in bash:
eval "$(python makealias.py)"
An example of a standard Unix program that works like this is tset with the -s option.

Running a Python print statement containing a bash command [duplicate]

This question already has answers here:
How do I execute a program or call a system command?
(65 answers)
Closed 5 years ago.
Is there a way for the Python print statement containing a bash command to run in the terminal directly from the Python script?
In the example below, the awk command is printed on the terminal.
#!/usr/bin/python
import sys
print "awk 'END{print NF}' file"
I can of course think of writing the print statement in a separate file and run that file as a bash script but is there a way to run the awk command directly from the python script rather than just printing it?
is there a way to run the awk command directly from the python script rather than just printing it?
Yes, you can use subprocess module.
import subprocess
subprocess.call(["ls", "-l"])
You can pipe your Python output into a Bash process, for example,
python -c "print 'echo 5'" | bash
will output
5
You could even use the subprocess module to do that from inside Python, if you wanted to.
But I am sure this is pretty bad design, and not a good idea. If you get your coding wrong, there's a risk you could allow hostile users to execute arbitrary commands on the machine running your code.
One solution is to use subprocess to run a shell command and capture its output, for example:
import subprocess
command = "awk 'END{print NF}' file"
p = subprocess.Popen([command], shell=True, bufsize=2000,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
print(''.join([line for line in child_stdout]))
child_stdout.close()
p.stdout.close()
Adjust bufsize accordingly based on the size of your file.

Python end program in shell [duplicate]

This question already has answers here:
Interacting with program after execution
(3 answers)
Closed 7 years ago.
I want a script to run an then finish on the python shell with all variables and methods:
$ python myprogram.py
...
program output
...
>>>
And with #!/usr/bin/python is posible? so I double-click and it just works?
Sounds like you want Python's i flag. From the help menu:
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
So the full command would be
python -i yourscriptname.py

How to run bash commands inside of a Python script [duplicate]

This question already has answers here:
Running Bash commands in Python
(11 answers)
Closed 2 years ago.
I am trying to run both Python and bash commands in a bash script.
In the bash script, I want to execute some bash commands enclosed by a Python loop:
#!/bin/bash
python << END
for i in range(1000):
#execute‬ some bash command such as echoing i
END
How can I do this?
Use subprocess, e.g.:
import subprocess
# ...
subprocess.call(["echo", i])
There is another function like subprocess.call: subprocess.check_call. It is exactly like call, just that it throws an exception if the command executed returned with a non-zero exit code. This is often feasible behaviour in scripts and utilities.
subprocess.check_output behaves the same as check_call, but returns the standard output of the program.
If you do not need shell features (such as variable expansion, wildcards, ...), never use shell=True (shell=False is the default). If you use shell=True then shell escaping is your job with these functions and they're a security hole if passed unvalidated user input.
The same is true of os.system() -- it is a frequent source of security issues. Don't use it.
Look in to the subprocess module. There is the Popen method and some wrapper functions like call.
If you need to check the output (retrieve the result string):
output = subprocess.check_output(args ....)
If you want to wait for execution to end before proceeding:
exitcode = subprocess.call(args ....)
If you need more functionality like setting environment variables, use the underlying Popen constructor:
subprocess.Popen(args ...)
Remember subprocess is the higher level module. It should replace legacy functions from OS module.
I used this when running from my IDE (PyCharm).
import subprocess
subprocess.check_call('mybashcommand', shell=True)

how to run a .bat file in python? [duplicate]

This question already has answers here:
Run a .bat file using python code
(9 answers)
Closed 6 years ago.
call python 'D:\chan.bat'
"set of python statements is stored in notepad and saved as .bat extension.
how to run these statements in python.what can be the syntax?"
I think this is usually done using the subprocess module:
from subprocess import call
call("D:\chan.bat")
However a normal call doesn't give you back much information. You might need the power of a Popen object:
from subprocess import Popen
Popen("D:\chan.bat")
Edit:
You might need to take out the single quotes for this to work.
"'D:\chan.bat'" -> "D:\chan.bat"
If you don't need to interact with the script, wouldn't this work?
import os
os.system("d:\\chan.bat")
I have no Windows box to test it.
Here is what I try on Mac OS
Dinh-Phams-MacBook-Pro:tmp dinhpham$ cat > t.bat
print "abc"
Dinh-Phams-MacBook-Pro:tmp dinhpham$
Dinh-Phams-MacBook-Pro:tmp dinhpham$ python t.bat
abc
Python interpreter does not care about .py extension
If you want to load .bat file as Python module, just use
imp.load_source(path_to_file)
Command can be passed to python as follows:
[avasal#avasal]$ python -c "print 'a' + 'b'"
ab
[avasal#avasal]$
In python --help you can see, -c cmd : program passed in as string (terminates option list), In your batch file, you can make use of this option.

Categories

Resources