How to use python to write a linux shell command? - python

I want to use python to write a shell command... that I can customize some paths in my config file, that I can "shortcut" to these paths directly, not need to "cd" and "cd" again and again...
I want to use python, because I don't know anything about bash. Is that possible ?if yes, could you give me any idea about how to use python to fullfill this shell command...
Thanks !

You have to give a look to the os library of python https://docs.python.org/2/library/os.html
The os.path module helps you to deal with paths. https://docs.python.org/2/library/os.path.html#module-os.path
With the subprocess module you can also execute commands, configure timouts (if the command hangs out), check the result, etc https://docs.python.org/2/library/subprocess.html

Related

Find the location of the bash executable on windows from python

I'm writing a program that executes short shell one liners (potentially including pipes and background tasks etc), and I'd like to make it "just work" cross platform as much as possible.
For mac/linux the following seems to work well:
shell = os.environ.get("SHELL", "/bin/bash")
subprocess.Popen([shell, "-c", script_content])
However given that on windows:
SHELL isn't usually set
Assuming that bash is installed, a usable bash executable might be found in a variety of different places
What's the best way to make this work as reliably as possible in windows?
Are you looking for C:\Windows\System32\cmd.exe?
And if you are doing cross platorm you could use sys.platorm to find the platform the user is using.
On Window, 'COMSPEC' holds the name of the current command program. You can write unconditional lookup to lookup in the environemnt. Usually, better to take this approach, as in many cases, python script may be executed from 'git-bash', WSL or similar. No need to explicitly program for specific platform.
First Using SHELL
If none, use COMSPEC
See: https://en.wikipedia.org/wiki/COMSPEC
If you have Windows git client installed, you should have git bash, so in a CMD window:
set SHELL="c:\Program Files\Git\bin\bash.exe"
then you can run you python program.

Python - running a script as a service with a name other than 'python'

I have a set of python scripts which I run as a daemon services. These all work great, but when all the scripts are running and I use top -u <USER>, I see all my scripts running as python.
I would really like to know which script is running under which process id. So is there any way to execute a python script as a different process name?
I'm stuck here, and I'm not ever sure what terms to Google. :-)
Note: I'm using Ubuntu Linux. Not sure if the OS matters or not.
Try using setproctitle. It should work fine on Linux.
Don't have a linux system here to test this on appropriately, but if the above doesn't work, you should be able to use the same trick they use for things like gzip etc.
The script has to tell what to run it at the top like this:
#!/usr/local/bin/python
Use a softlink like this:
ln -s /usr/local/bin/python ~/bin/myutil
Then just change your script to
#!~/bin/myutil
and it should show up that way instead. You may need to use a hard link instead of a soft link.
Launching a python script using the python script itself (and file associations and/or shell magic) is not very portable, but you can use similar methods on nearly any OS.
The easiest way to get this is using she bang. The first line of your python script should be:
#!/usr/bin/python
or
#!/usr/bin/python3
depending upon whether you use python or python3
and then assign executable permissions to the script as follows:
chmod +x <scriptname>
and then run the script as
./scriptname
this will show up as scriptname in top.

Calling multiple commands using os.system in Python

I would like to invoke multiple commands from my python script.
I tried using the os.system(), however, I'm running into issues when the current directory is changed.
example:
os.system("ls -l")
os.system("<some command>") # This will change the present working directory
os.system("launchMyApp") # Some application invocation I need to do.
Now, the third call to launch doesn't work.
os.system is a wrapper for the C standard library function system(). Its argument can be any valid shell command as long as it fits into the memory reserved for environment and argument lists of a process.
So, delimit each command with a semicolon or a newline and they will be executed one after another in the same environment.
os.system(" ls -l; <some command>; launchMyApp")
os.system('''
ls -l
<some command>
launchMyApp
''')
Try this
import os
os.system("ls -l")
os.chdir('path') # This will change the present working directory
os.system("launchMyApp") # Some application invocation I need to do.
Each process has its own current working directory. Normally, child processes can't change parent's directory that is why cd is a builtin shell command: it runs in the same (shell) process.
Each os.system() call creates a new shell process. Changing the directory inside these processes has no effect on the parent python process and therefore on the subsequent shell processes.
To run multiple commands in the same shell instance, you could use subprocess module:
#!/usr/bin/env python
from subprocess import check_call
check_call(r"""set -e
ls -l
<some command> # This will change the present working directory
launchMyApp""", shell=True)
If you know the destination directory; use cwd parameter suggested by #Puffin GDI instead.
It’s simple, really.
For Windows separate your commands with &, for Linux, separate them with ;.
str.replace is a very good way to approach the problem, used in the example below:
import os
os.system('''cd /
mkdir somedir'''.replace('\n', ';')) # or use & for Windows
When you call os.system(), every time you create a subshell - that closes immediately when os.system returns (subprocess is the recommended library to invoke OS commands). If you need to invoke a set of commands - invoke them in one call.
BTW, you may change working director from Python - os.chdir
Try to use subprocess.Popen and cwd
example:
subprocess.Popen('launchMyApp', cwd=r'/working_directory/')
os.system("ls -l && <some command>")
You can change back to the directory you need to be in with os.chdir()
Just use
os.system("first command\nsecond command\nthird command")
I think you have got the idea what to do
Note: This is not a very reliable approach if you are doing a complex
job using CLI tools. Popen and subprocess methods are better there.
Although small task link copy, move, list will work fine
.

python open applications through your program

I want my program to open iTunes during runtime. How do I implement this ?
I looked around for answers but didn't get any concrete complete answers. Till now, all I know is I could use the os module and then call the os.system() function to open iTunes. If this is right, what goes into the brackets ?
I have a Mac OS X machine.
One straightforward way to do this on Mac OS X will be to use the open command:
os.system("open -a iTunes")
There are undoubtedly other ways of doing this (e.g, using the Cocoa/Python bridge), but this is the simplest.
This should be able to help you.
From the article linked above...
import sys, string, os, arcgisscripting
os.chdir( 'c:\\documents and settings\\flow_model' )
os.system( '"C:\\Documents and Settings\\flow_model\\flow.exe"' )
Use subprocess.call() if you want to simply run an executable.
os.system() run the command in a subshell, which generates an unnecessary extra process and slightly different behavior depending on the operating system/console used (for example cmd.exe have different escaping than bash)
Read subprocess, is better than os.system in your case.
Subprocess module: http://docs.python.org/2/library/subprocess.html

TO initiate Python shell

You can use subprocess.call("/usr/bin/python") to open Python shell within a piece of Python code. Now my question is is it possible to predefine some variables/functions before initialization of this shell? In other words, inside Python code, I can define a bunch of useful variables and functions and I want them to be available in the Python shell opened later by subprocess call. It is useful in the sense that sometimes you want a customized Python shell to test your environment.
You can do this using the -i switch. This will run a script, and then drop into the interpreter for interactive use.
python -i scriptname.py
Not directly, but I wouldn't do it this way anyways; I'd use code.
Yes, that's something that it's possible and it's useful. In fact, that's something that django provides with the python manage.py shell command.
Looking at the source code for this command should be helpful not only as an example to open a shell with some default configuration, but also to use any shell you like (ipython, bpython or the default one).

Categories