下面脚本的输出是正确的,但每次打印一行时,它也会打印错误。
import os
for pid in os.listdir ( '/proc' ) :
if pid.isdigit ( ) :
try :
p = open ( os.path.join ( '/proc' , pid , 'cmdline' ) , 'r' )
CMD = p.read ( )
try:
tty = os.ttyname ( int ( pid ) )
except OSError as error:
print(error)
print ( int ( pid ) , CMD , tty )
p.close()
except OSError as error:
continue输出:
(1, '/sbin/init\x00splash\x00', '/dev/pts/0')
(2, '', '/dev/pts/0')
[Errno 25] Inappropriate ioctl for device
(3, '', '/dev/pts/0')
[Errno 9] Bad file descriptor
(4, '', '/dev/pts/0')
[Errno 9] Bad file descriptor
etc....发布于 2020-10-01 22:38:14
您看到错误,因为指定的文件描述符与任何终端设备都没有关联。
>>> r, w = os.pipe()
>>> os.ttyname(r)
Traceback (most recent call last):
File "<input>", line 1, in <module>
OSError: [Errno 25] Inappropriate ioctl for device
>>> r
6
>>> os.ttyname(6)
Traceback (most recent call last):
File "<input>", line 1, in <module>
OSError: [Errno 25] Inappropriate ioctl for device当它被关联时。
>>> import os
>>> master, slave = os.openpty()
>>> os.ttyname(master)
'/dev/ptmx'
>>> master
4
>>> os.ttyname(4)
'/dev/ptmx'snippet shared上的一些小改进:
import os
for pid in os.listdir('/proc' ):
if pid.isdigit():
try:
with open(os.path.join('/proc', pid, 'cmdline'), 'r') as p: # context way manages file close on its own
CMD = p.read()
tty = os.ttyname(int(pid))
print(f"PID: {int( pid )}, CMD: {CMD}, TTY: {tty}")
except OSError as error: # Can be handled with same Same exception
print(error)
# continue # Since there are no further lines of code hencehttps://stackoverflow.com/questions/64157297
复制相似问题