views:

81

answers:

3

Hello,

I have a file a.txt with lines of commands I want to run, say:

echo 1
echo 2
echo 3

If I was on csh (unix), I would have done source a.txt and it would run. From python I want to run os.execl with it, however I get:

>>> os.execl("source", "a.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/os.py", line 322, in execl
    execv(file, args)
OSError: [Errno 2] No such file or directory

How to do it?

+1  A: 

Do you just want to run a script? In that case, you can replace "source" with "bash" and probably get what you want.

If you want the thing-being-sourced to have side-effects on the Python process, like setting environment variables or something, you are probably out of luck.

Walter Mundt
I suggest you remove the word "probably" in that last sentence.
Bryan Oakley
Well, technically you could try and parse out the script, determine what it would do, and then apply those changes to Python's os.env, etc. It's probably a terrible idea, but it's possible; thus "probably."
Walter Mundt
+1  A: 

You are not supplying the full path to source, and os.execl needs the path.

If you want to use the PATH env variable, you should use os.execlp.

See the os module documentation.

Although, as @Walter mentions, you probably want /bin/bash instead of source:

os.execl("/bin/bash", "a.txt")
Stephen
+2  A: 

source is not an executable program, so you can't execute it directly. Rather, it is a builtin command in the shell. You would need to launch that shell instead if you really needed access to it. But if you just want to run the script, you don't need to use source at all – just have the shell execute your script directly:

os.execl("/bin/bash", "a.txt")
Owen S.