joseph
joseph

Reputation: 123

How do I get the pid of a spawned process using pexpect?

I am using pexpect to spawn a bash shell and then using sendline to execute other processes within the bash shell.

Is there any way to get the pid of the spawned bash shell?
How can I get the pid of the process that I have started within bash?

Upvotes: 3

Views: 2076

Answers (2)

Korcan Karaokçu
Korcan Karaokçu

Reputation: 557

Manuel's answer is actually incorrect. But it's not his fault, it's a fault of pexpect instead.

Invoking this python code

child=pexpect.spawn("gdb")
child.pid

gave me the pid value of 14470. But when I controlled it via bash, I saw that gdb had the pid value of 14473. This probably happens because pexpect invokes a wrapper and returns the pid of the wrapper instead of the real process.

Upvotes: 4

Manuel Miranda
Manuel Miranda

Reputation: 823

If you check the documentation of the spawn class you'll find that you can get the pid of the spawned process with the pid attribute, so

spawnedBash = pexpect.spawn('bash')
print(spawnedBash.pid)

should print your spawned process's pid

Upvotes: 5

Related Questions