Python linux which command

techtonik / find_executable.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

#!/usr/bin/env python
# https://gist.github.com/4368898
# Public domain code by anatoly techtonik
# AKA Linux `which` and Windows `where`
# For Python 3 you probably want
# https://docs.python.org/dev/library/shutil.html#shutil.which
import os
import sys
def find_executable ( executable , path = None ):
«»»Find if ‘executable’ can be run. Looks for it in ‘path’
(string that lists directories separated by ‘os.pathsep’;
defaults to os.environ[‘PATH’]). Checks for all executable
extensions. Returns full path or None if no command is found.
«»»
if path is None :
path = os . environ [ ‘PATH’ ]
paths = path . split ( os . pathsep )
extlist = [ » ]
if os . name == ‘os2’ :
( base , ext ) = os . path . splitext ( executable )
# executable files on OS/2 can have an arbitrary extension, but
# .exe is automatically appended if no dot is present in the name
if not ext :
executable = executable + «.exe»
elif sys . platform == ‘win32’ :
pathext = os . environ [ ‘PATHEXT’ ]. lower (). split ( os . pathsep )
( base , ext ) = os . path . splitext ( executable )
if ext . lower () not in pathext :
extlist = pathext
# Windows looks for binaries in current dir first
paths . insert ( 0 , » )
for ext in extlist :
execname = executable + ext
for p in paths :
f = os . path . join ( p , execname )
if os . path . isfile ( f ):
return f
else :
return None
if __name__ == ‘__main__’ :
if sys . argv [ 1 :]:
print ( find_executable ( sys . argv [ 1 ]))
else :
print ( ‘usage: find_executable.py ‘ )

Источник

Where Is Python Installed

Where Is Python Installed

  1. Use the dirname() Function to Find the Installation Folder of Python
  2. Use the where Command to Find the Installation Folder of Python
  3. Use the which Command to Find the Installation Folder of Python

The installation folder of any software or application has some significance since it points us to the exact place where most of the related files and folders related to it can be found. The same goes for Python; we have to install it at a specific location where it stores the language’s modules and basic framework.

In this tutorial, we will learn how to view the path of the installation folder of Python.

Use the dirname() Function to Find the Installation Folder of Python

The os library is used to interact with the Operating System and has functions available to retrieve full paths of the files. The dirname() function from this library can be used to retrieve the directory from the specified file’s path.

To return the installation directory, we pass the sys.executable to this function from the sys library. The sys.executable returns the path of the binary executable of the Python interpreter.

The following code shows how to use this.

import os import sys  print(os.path.dirname(sys.executable)) 

Use the where Command to Find the Installation Folder of Python

We can directly use the where python command in the command prompt to find Python’s installation folder in windows.

C:\>where python C:\Python\Python 3.9\python.exe 

Use the which Command to Find the Installation Folder of Python

In Linux and macOS, we can use the which python command in the terminal to view Python’s installation path.

Источник

Finding the command for a specific PID in Linux from Python

I’d like to know if it’s possible to find out the «command» that a PID is set to. When I say command, I mean what you see in the last column when you run the command «top» in a linux shell. I’d like to get this information from Python somehow when I have a specific PID. Any help would be great. Thanks.

7 Answers 7

Using a /proc files has a disadvantage of lower portability, which may or may not be a concern. Here’s how you can use the standard shell command for that

Note the two -w options that instructs ps to not truncate the output (which it does by default)

Reading its output from python is as simple as calling a single function subprocess.check_output() documented here.

ps works by reading the virtual files in /proc. So much for the well-defined POSIX interface (which one was that, anyway?).

Listen, I would have marked you both as correct answers but I couldn’t. Pavel’s answer just seemed to be more of what I was looking for but the answer given for DigitalRoss was great too. Upvotes for both.

@Nick Stinemates, @Michael Foukarakis. Hey, I know how ps works (yes, it indeed reads files in /proc ). But when instead of /proc they’ll invent /foobar system, you’ll have to rewrite your program. Anyway, maybe I’ve been braindamaged by working in LSB workgroup, but you really should stick to standards where it’s enough for you—which is the case under consideration.

This command will output the command line args, but separate them with spaces. If you’re trying to split the arguments back into a list of strings, you won’t be able to differentiate between args, and args with spaces. (Which you can do with /proc/$PID/cmdline )

An interesting Python package is psutil.

For example, to get the command for a specific PID:

import psutil pid = 1234 # The pid whose info you're looking for p = psutil.Process(pid) print(p.cmdline()) 

The last line will print something like [‘/usr/bin/python’, ‘main.py’] .

A more robust way to get this information, being careful if the pid represents a process no longer running:

import psutil pid = 1234 # The pid whose info you're looking for if pid in psutil.get_pid_list(): p = psutil.Process(pid) print(p.cmdline()) 

Look in /proc/$PID/cmdline

Look in /proc/$PID/cmdline , and then os.readlink() on /proc/$PID/exe .

/proc/$PID/cmdline is not necessarily going to be correct, as a program can change its argument vector or it may not contain a full path. Three examples of this from my current process list are:

  • avahi-daemon: chroot helper
  • qmgr -l -t fifo -u
  • /usr/sbin/postgrey —pidfile=/var/run/postgrey.pid —daemonize —inet=127.0.0.1:60000 —delay=55

That first one is obvious — it’s not a valid path or program name. The second is just an executable with no path name. The third looks ok, but that whole command line is actually in argv[0] , with spaces separating the arguments. Normally you should have NUL separated arguments.

All this goes to show that /proc/$PID/cmdline (or the ps(1) output) is not reliable.

However, nor is /proc/$PID/exe . Usually it is a symlink to the executable that is the main text segment of the process. But sometimes it has » (deleted) » after it if the executable is no longer in the filesystem.

Also, the program that is the text segment is not always what you want. For instance, /proc/$PID/exe from that /usr/sbin/postgrey example above is /usr/bin/perl . This will be the case for all interpretted scripts (#!).

I settled on parsing /proc/$PID/cmdline — taking the first element of the vector, and then looking for spaces in that, and taking all before the first space. If that was an executable file — I stopped there. Otherwise I did a readlink(2) on /proc/$PID/exe and removed any » (deleted) » strings on the end. That first part will fail if the executable filename actually has spaces in it. There’s not much you can do about that.

BTW. The argument to use ps(1) instead of /proc/$PID/cmdline does not apply in this case, since you are going to fall back to /proc/$PID/exe . You will be dependent on the /proc filesystem, so you may as well read it with read(2) instead of pipe(2), fork(2), execve(2), readdir(3). write(2), read(2). While ps and /proc/$PID/cmdline may be the same from the point of view of lines of python code, there’s a whole lot more going on behind the scenes with ps.

Источник

Is there a Python equivalent to the ‘which’ command [duplicate]

Put another way, is there a cross-platform way of knowing which file will be executed by subprocess.Popen(file) without first executing it?

By default, subprocess inherents the environment of the parent process. So for any executable in the PATH (or the OS in question’s equivalent) you don’t need to specifiy the location.

3 Answers 3

Python 3.3 added shutil.which() to provide a cross-platform means of discovering executables:

Return the path to an executable which would be run if the given cmd was called. If no cmd would be called, return None.

>>> shutil.which("python") '/usr/local/bin/python' >>> shutil.which("python") 'C:\\Python33\\python.EXE' 

Unfortunately, this has not been backported to 2.7.x.

Python source for version 3.3’s implementation of shutil.which is here (only a few dozen lines): hg.python.org/cpython/file/6860263c05b3/Lib/shutil.py#l1068

if you change line 1110 to if any([cmd.lower().endswith(ext.lower()) for ext in pathext]) (turn the generator to a list) than it will work in python 2.7.

An option for Python 2 and 3:

from distutils.spawn import find_executable find_executable('python') # '/usr/bin/python' find_executable('does_not_exist') # None 

find_executable(executable, path=None) simply tries to find ‘executable’ in the directories listed in ‘path’. Defaults to os.environ[‘PATH’] if ‘path’ is None . Returns the complete path to ‘executable’ or None if not found.

Keep in mind that unlike which , find_executable does not actually check that the result is marked as executable. You may want to call os.access(path, os.X_OK) to check that on your own if you want to be certain that subprocess.Popen will be able to execute the file.

Also of note, shutil.which of Python 3.3+ has been backported and made available for Python 2.6, 2.7, and 3.x via the 3rd-party module whichcraft.

It is available for installation via the aforementioned GitHub page (i.e. pip install git+https://github.com/pydanny/whichcraft.git ) or the Python package index (i.e. pip install whichcraft ). It can be used like such:

from whichcraft import which which('wget') # '/usr/bin/wget' 

Источник

Читайте также:  Linux debian установленные пакеты
Оцените статью
Adblock
detector