0

I want to us traffic control of the Linux kernel with Python to simulate lost, corrupt and duplicate packages. I'm already able to configure this with the Linux Terminal, but I have to use python.

bash cmd works:

tc filter show dev eth1

python doesn't work:

>>> subprocess.call(["tc", "filter", "show", "dev", "eth1"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/subprocess.py", line 470, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.6/subprocess.py", line 623, in __init__
    errread, errwrite)
  File "/usr/lib/python2.6/subprocess.py", line 1141, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Thanks.

chepner
  • 497,756
  • 71
  • 530
  • 681
checkThisOut
  • 621
  • 1
  • 5
  • 18

2 Answers2

3

The python subprocess doesn't know about your shell environment. So provide absolute path to your command, something like:

subprocess.call(["/sbin/tc", "filter", "show", "dev", "eth1"])

find the exact location with command which tc in your shell.

wim
  • 338,267
  • 99
  • 616
  • 750
  • That's simply not true. @checkThisOut may not have `/sbin` in the `PATH`. If it's there, the call will work without having to add the full path. It's advisable, though. – Ricardo Cárdenes Aug 13 '14 at 13:15
  • 1
    Also worth mentioning that you should run the Python with the same user that has the privileges that are required to run the `tc` command. – Burhan Khalid Aug 13 '14 at 13:21
0

The basic way if you don't need any special control is to use os.system() to launch a command as if you were in your shell command line (no need to specify the full path if in your $PATH):

import os
os.system("tc filter show dev eth1")

This should work exactly as if you did in your cmd:

$ tc filter show dev eth1
daouzli
  • 15,288
  • 1
  • 18
  • 17
  • 1
    This removes the error checking provided by `subprocess`. What advantage does it offer? – John Zwinck Aug 13 '14 at 13:23
  • I don't necessarily recommend the use of `os.system`. But in particular basic needs it could be more interesting than using a command with more parameters as `shell=True` to have benefits of context,... – daouzli Aug 13 '14 at 13:28