繁体   English   中英

通过子进程运行命令/程序

[英]Running commands/programs with subprocess

我是python subprocess模块的新手。

文档提供了以下示例:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

我试过的是:

>>> import subprocess
>>> subprocess.check_output(["cd", "../tests", "ls"])
/usr/bin/cd: line 4: cd: ../tests: No such file or directory
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 620, in check_output
    raise CalledProcessError(retcode, process.args, output=output)
subprocess.CalledProcessError: Command '['cd', '../tests', 'ls']' returned non-zero exit status 1

我很困惑,因为这是我的文件结构:

   /proj
      /cron
         test_scheduler.py
      /tests
         printy.py
         test1.py
         test2.py
         ...

这些也是我的其他尝试:

>>> subprocess.check_output(["cd", "../tests", "python", "printy.py"])
/usr/bin/cd: line 4: cd: ../tests: No such file or directory
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 620, in check_output
    raise CalledProcessError(retcode, process.args, output=output)
subprocess.CalledProcessError: Command '['cd', '../tests', 'python', 'printy.py']' returned non-zero exit status 1


>>> subprocess.check_output(["cd", "../tests;", "ls"])
/usr/bin/cd: line 4: cd: ../tests;: No such file or directory
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 620, in check_output
    raise CalledProcessError(retcode, process.args, output=output)
subprocess.CalledProcessError: Command '['cd', '../tests;', 'ls']' returned non-zero exit status 1

尽可能避免shell=True

在这种情况下,您当然可以避免。 您面临的问题是: cd是内置的shell。 它不是可以从外部调用的命令/程序/实用程序。 您需要安装在外壳中才能使cd正常工作。 您可以做的是更改当前目录。 执行命令。 然后回到您的原始目录。

您需要执行以下操作:

pathBefore = os.getcwd()
os.chdir("/path/to/your/directory")
subprocess.check_output(["ls"])
os.chdir(pathBefore) # get back to the path we were in before

更新@JFSebastian指出的一种更好的方法是对check_output调用使用附加的cwd参数

tests目录的相对路径取决于脚本从何处运行。 我建议调用subprocess.check_output(["pwd"])来检查您的位置。

同样,您不能像在尝试使用["cd", "../tests", "python", "printy.py"]一样在同一调用中组合两个命令。 您需要分别使用["cd", "../tests"]["python", "printy.py"]进行两个单独的调用。

错误消息很清楚:

/ usr / bin / cd:第4行:cd​​:../ tests:没有这样的文件或目录

那就是您已经成功启动了失败的/usr/bin/cd程序并打印了错误消息。

如果要从../tests目录运行ls命令,请../tests

import os
import subprocess

cwd = os.path.join(get_script_dir(), '../tests')
output = subprocess.check_output(['ls'], cwd=cwd)

其中get_script_dir()

注意:请勿在目录中使用相对路径-可以从其他目录运行脚本-在这种情况下,相对路径会失败。

我想您在这里缺少争论。
这是我写过的唯一python脚本的摘录:

#!/usr/local/bin/python

from subprocess import call
...
call( "rm " + backupFolder + "*.bz2", shell=True )

请注意该调用结束时的shell=True

暂无
暂无

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

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