0

I am trying to created aliases for tcsh from a python script (running Python 2.7.1). Once the aliases are created I want to use them in the same shell I ran the python script in.

I tried:

os.system('alias test "echo test"')

but I get the following error:

sh: line 0: alias: test: not found
sh: line 0: alias: echo test: not found

I then tried:

os.system(r"""/bin/csh -i -c 'alias test "echo test"'""")

And then no errors occurred, but the alias did not register, and therefore I could not use it.

The result I'm looking for is this:

tcsh>python my_script.py
tcsh>test
test

Thanks!

OHT
  • 15
  • 3
  • 1
    As an aside, here's the obligatory pointer to t?csh Considered Harmful. http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/ – tripleee Jan 01 '13 at 12:01

2 Answers2

1

Your python script cannot execute anything in the context of your shell. While you could use subprocess.call(..., shell=True) this would use a new shell and thus not update your existing shell.

The only way to do what you want is to make your python script write valid shell commands to stdout and then, instead of just executing it, you need to make your shell evaluate the output of your python script.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • I was hoping there was a nicer way, oh well I'll try it like your answer. Thanks! – OHT Jan 01 '13 at 12:14
1

os.system executes that command in a subshell (the bourne shell by the look of it), so even if your syntax was correct alias test="echo test", it would not persist after the call (since the subshell closed).

But this seems like an XY question. You ask about Y - the solution you had in mind, and not about X - your problem.

If you simply want to create a bunch of aliases at once, why not use a c-shell script!? (Why you are torturing yourself with c-shell is another matter entirely).

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Thanks for the syntax correction, although running the command in the tcsh `alias test "echo test"` works fine. Unfortunately we are forced to use tcsh and I can't change it. Thanks anyway – OHT Jan 01 '13 at 12:16