我是否正确使用系统 call/subprocess 调用?

Am I using system call/subprocess call correctly?

这段代码运行失败:

import datetime
import subprocess

startdate = datetime.datetime(2010,4,9)
for i in range(1): 
    startdate += datetime.timedelta(days=1)

enddate = datetime.datetime(2010,4,10)
    for i in range(1): 
        enddate += datetime.timedelta(days=1)

subprocess.call("sudo mam-list-usagerecords -s \"" + str(startdate) + "\" -e \"" + str(enddate) + " --format csv --full")

程序运行时出现以下错误:

  File "QuestCommand.py", line 12, in <module>
subprocess.call("sudo mam-list-usagerecords -s \"" + str(startdate) + "\" -e \"" + str(enddate) + " --format csv --full")
  File "/usr/lib64/python2.7/subprocess.py", line 524, in call
return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception

我用其他方式运行多次使用此代码,更改引号等等。我对系统调用和使用 HPC 分配数据库还很陌生。我被卡住了,如果有人可以帮助我解决这个问题,那将非常有帮助。

谢谢!

当我第一次开始使用一些子流程方法时,我 运行 遇到了一些相同的问题。

像这样尝试 运行 您的代码:

import datetime
import subprocess
import shlex

startdate = datetime.datetime(2010, 4, 9) + datetime.timedelta(days=1)
enddate = datetime.datetime(2010, 4, 10) + datetime.timedelta(days=1)
command = (
    "sudo mam-list-usagerecords -s "
    + str(startdate)
    + "-e"
    + str(enddate)
    + " --format csv --full"
)

print(command)
print(type(command))
print(shlex.split(command))
subprocess.call(shlex.split(command))

输出:

sudo mam-list-usagerecords -s 2010-04-10 00:00:00-e2010-04-11 00:00:00 --format csv --full

class 'str'

['sudo', 'mam-list-usagerecords', '-s', '2010-04-10', '00:00:00-e2010-04-11', '00:00:00', '--format', 'csv', '--full']

(已编辑命令输出。)

当 kwarg shell 设置为默认的 False 时,命令可能必须是一个集合,这就是 shlex.split 所做的。

args should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.

Popen constructor

这个问题曾经让我很困惑,直到我在文档中找到它。

如果可能,传递包含您的命令名称及其参数的列表

subprocess.call(["sudo", "mam-list-usagerecords",
                 "-s", str(startdate),
                 "-e", str(enddate),
                 "--format", "csv",
                 "--full"])

这甚至不需要知道 shell 将如何处理命令行。