0

I want to start and stop an external program in Python3, on Linux. This program is an executable, called smip-tun, located in the same folder as the source code and I'd like to be able to execute and control it from there with relative names.

Unfortunately, this does not work:

smip_tun = 0

def start_smip_tun(self):
    smip_tun =  subprocess.Popen(['smip-tun',DEFAULT_SERIAL_PORT])

def end_smip_tun(self):
    smip_tun.terminate()
    print("end")

But says it cannot find smip-tun. Efforts to specify the relative directory have failed. I was trying with cwd but cannot figure it out.
Any advice?

Edit:

Made Smip-tun global but the issue persists.

New code:

smip_tun = 0

def start_smip_tun(self):
    global smip_tun
    smip_tun =  subprocess.Popen(['smip-tun',DEFAULT_SERIAL_PORT])

def end_smip_tun(self):
    global smip_tun
    smip_tun.terminate()
    print("end")

Error message:

  File "/home/sven/git/cerberos_manager/iot_network_api.py", line 40, in start_smip_tun
    smip_tun = subprocess.Popen(['smip-tun',DEFAULT_SERIAL_PORT])
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'smip-tun'
  • 2
    You need to declare `smip_tun` global, see [Using global variables in a function other than the one that created them](http://stackoverflow.com/q/423379/45249) – mouviciel Nov 28 '16 at 12:47
  • @mouviciel This is a perfectly fine answer ;) – filmor Nov 28 '16 at 12:51
  • More specifically, add a `global smip_tun` statement to the beginning of the `start_smip_tun()` function. – martineau Nov 28 '16 at 13:08
  • I've incoporated your advice, but the issue persists. –  Nov 28 '16 at 14:33
  • You had two issues. The `global` advice solved the one you didn't see because of the second one. Now, you have to specify the path of `smip-tun` or include that path in your `PATH` environment variable (e.g., `export PATH=.:$PATH`). – mouviciel Nov 29 '16 at 10:23
  • Yes indeed, but my main question was on how to do that relative to the directory the script itself is executing in. Smip-tun is located in the same directory as the .py file. –  Nov 29 '16 at 12:10
  • I am a bit slow. The mistake is that I need to specify "./smip-tun" to execute, not smip-tun –  Nov 29 '16 at 12:28

1 Answers1

1
import os

os.chdir('.') # or change the . for the full path directory.

smip_tun =  subprocess.Popen(['smip_tun',DEFAULT_SERIAL_PORT])

Also make sure your app do not have any extension, like smip-tun.py and smip-tun.sh

Wondercricket
  • 7,651
  • 2
  • 39
  • 58