Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining PID of a shell / python script inside the script itself

How can I obtain the PID of a shell script inside the script itself and pass the same to another script?

like image 441
Akhil P Sudhakaran Avatar asked Sep 18 '15 09:09

Akhil P Sudhakaran


People also ask

How do I find the process ID of a running script in Unix?

A process is nothing but running instance of a program and each process has a unique PID on a Unix-like system. The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.

Can you call a shell script from Python?

If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.


2 Answers

The process ID of the current process can be retrieved with os.getpid().

import os

print("This process has the PID", os.getpid())

In bash, you can use $$ to get the PID of the bash instance running the script.

like image 93
user1514631 Avatar answered Oct 19 '22 06:10

user1514631


It's years and years later but in UNIX systems $$ is a type of variable for shell PID.

You should try;

echo $$

Code above returns the PID of the shell you are working at.

And also Python's os library has a method called getpid

import os
os.getpid()

You can store this variable in temp file in /tmp/anyFile path. And by doing this, other script you mentioned could access this file

like image 20
Baran Yeni Avatar answered Oct 19 '22 07:10

Baran Yeni