简体   繁体   English

从交互式IPython shell中的函数调用shell命令

[英]Invoking shell-command from function in interactive IPython shell

I have just been playing around with IPython. 我刚刚玩过IPython。 Currently I am wondering how it would be possible to run a shell-command with a python variable within a function. 目前我想知道如何在函数中运行带有python变量的shell命令。 For example: 例如:

def x(go):
    return !ls -la {go}

x("*.rar")

This gives me "sh: 1: Syntax error: end of file unexpected". 这给了我“sh:1:语法错误:文件结束意外”。 Could anybody please give me a clue on how to let my "x"-function invoke ls like "ls -la *.rar"? 有人可以给我一个关于如何让我的“x”函数调用ls -la * .rar“的线索吗? There are *.rar files in my working directory. 我的工作目录中有* .rar文件。

Thank you in advance, Rainer Rainer,提前谢谢你

If you look at the history command output, you'll see that to call external programs ipython uses _ip.system method. 如果查看history命令输出,您将看到调用外部程序ipython使用_ip.system方法。

Hence, this should work for you: 因此,这应该适合你:

def x(go):
    return _ip.system("ls -la {0}".format(go))

However, please note that outside ipython you should probably use subprocess.Popen . 但是,请注意,外IPython中,你应该使用subprocess.Popen

There was a bug in the "!" “!”中有一个错误 shell access that made the expansion of "function scoped variables" fail. shell访问使得“函数范围变量”的扩展失败。 Your ipython's version might be affected. 您的ipython版本可能会受到影响。

You can avoid it by doing yourself the variable expansion: 您可以通过自己进行变量扩展来避免它:

def x(go):
    return get_ipython().getoutput("ls -la {0}".format(go))

Depending on what you wanted to accomplish, this may be the better way: 根据您想要完成的任务,这可能是更好的方法:

In [50]:  %alias x ls -la %l


In [51]:  x *.rar

          -rw-r--r-- 1 dubbaluga users 45254 Apr  4 15:12 schoolbus.rar

Maybe its easier to use Python for this case: 也许在这种情况下更容易使用Python:

import glob

files = glob.glob('*.rar')   

While subprocess.Popen is probably the way to go as @jcollado said, just for completeness there is the os.system command to immediately send a command to the shell. 虽然subprocess.Popen可能就像@jcollado所说的那样,但为了完整性,有os.system命令立即向shell发送命令。 However, the subprocess module is almost always a better choice than os.system or os.spawn. 但是,子进程模块几乎总是比os.system或os.spawn更好的选择。

Also, depending on what you are trying to do you may want to use python commands to interact with the operating system rather than passing commands out to a shell. 此外,根据您尝试执行的操作,您可能希望使用python命令与操作系统进行交互,而不是将命令传递给shell。 If you want to deal with lists of files for instance, os.walk would likely result in cleaner and more portable code than grabbing the directory list through shell commands. 例如,如果你想处理文件列表,os.walk可能会产生比通过shell命令获取目录列表更清晰,更可移植的代码。 You can look at the documentation for Python's OS module here . 您可以在此处查看Python OS模块的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM