python - 返回文件或目录未找到,但 bash 命令中未提及文件或目录?

标签 python linux bash subprocess paramiko

我正在尝试使用收到的特定命令从数据库中转储信息。

 db_dump = open('{}/dbdump.txt'.format(directory_name), 'w+')
    foo = subprocess.call('PGPASSWORD="-------" pg_dump -h vm-postgres -d "qa-test{}db" -U "qatest" -a -x'.format(str(driverlabelnum)), shell=True)
    print str(foo)
    db_dump.write(foo)
    db_dump.close()
    print "Done dumping"

当我将它复制粘贴到命令行时它工作得很好,但是当我尝试通过 subprocess.call() 使其自动化时出现错误。

我尝试了几种不同的方法,但我一直遇到这个错误...

    Traceback (most recent call last):
  File "/home/csd-user/test/libs/utils/butler.py", line 427, in <module>
    main()
  File "/home/csd-user/test/libs/utils/butler.py", line 424, in main
    b.log_bug_exec(url)
  File "/home/csd-user/test/libs/utils/butler.py", line 52, in log_bug_exec
    cls.process_file(stdout)
  File "/home/csd-user/test/libs/utils/butler.py", line 109, in process_file
    cls.create_artifacts(nums[0], nums[1])
  File "/home/csd-user/test/libs/utils/butler.py", line 269, in create_artifacts
    foo = csd_shell_lib.check_output('PGPASSWORD="-------" pg_dump -h vm-postgres -d "qa-test{}db" -U "qatest" -a -x'.format(str(driverlabelnum)))
  File "/home/csd-user/test/libs/jupiter/csd_shell_lib.py", line 70, in check_output
    return subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
  File "/opt/cs/lib/python2.7/subprocess.py", line 566, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/opt/cs/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/opt/cs/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

我知道 subprocess.call 命令将命令拆分为 substrings(.split(' ')) 的数组/列表,并且它自己调用 PGPASSWORD=""。但是,我不知道如何避免这种情况发生,也无法在网上找到它。

附言我遇到的另一个问题是 Paramiko 试图获取文件时 Errno 13 权限被拒绝。我不知道/不明白如何在程序不提示我输入密码的情况下以 susudo 身份登录(仅使用单数 paramiko 命令)(我可以做到使用 ssh,但我宁愿不使用)。

最佳答案

PGPASSWORD 是一个环境变量。当您必须提供特定的环境变量时,您不能使用 subprocess.call。您可以改用 subprocess.Popen 并传递环境变量 as a dedicated parameter .

import os, subprocess
env = os.environ.copy()
env['PGPASSWORD'] = '------'
subprocess.Popen('pg_dump -h vm-postgres -d "qa-test{}db" -U "qatest" -a -x'.format(str(driverlabelnum)), env=env, shell=True)

关于python - 返回文件或目录未找到,但 bash 命令中未提及文件或目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31432792/

相关文章:

javascript - 算法在一个非常大的数组中查找重复项

python - Azure:使用 Python 创建公共(public) IP 地址

python - 如何加载 tumblr 上的所有笔记?

linux - (bash) 使用 cat 将多行文本缩进到 $VAR?

linux - 检查是否已将私有(private) ssh-key 添加到 ssh-agent

java - Git 多樱桃选择与 Bash 抛出错误

python - 如果名称在列表中,则选择 Pandas 数据框的列,或创建默认值并删除其余列

c - 我应该使用什么方法来知道在进程 fork 然后执行后打开了哪些 fds

c++ - 我如何在 linux 中创建一个 unicode 文件名?

linux - 在 awk 命令中使用 pstree