运行脚本时如何将布尔参数传递到子进程

问题描述 投票:0回答:1

我正在使用子进程来运行脚本。脚本参数之一是布尔值。当我尝试传递此参数时,出现错误。

这是我的代码

scriptF = 'pythongScript.py'
arg1= 'arg1'
arg2= 'arg2'
arg3= True

subprocess.call(["python", scriptF, "--arg1", file1, "--arg2", file2, "--arg3", arg3])

这是我收到的错误消息

/usr/lib/python3.6/subprocess.py in call(timeout, *popenargs, **kwargs)
    285     retcode = call(["ls", "-l"])
    286     """
--> 287     with Popen(*popenargs, **kwargs) as p:
    288         try:
    289             return p.wait(timeout=timeout)

/usr/lib/python3.6/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors)
    727                                 c2pread, c2pwrite,
    728                                 errread, errwrite,
--> 729                                 restore_signals, start_new_session)
    730         except:
    731             # Cleanup if the child failed starting.

/usr/lib/python3.6/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1293                             errread, errwrite,
   1294                             errpipe_read, errpipe_write,
-> 1295                             restore_signals, start_new_session, preexec_fn)
   1296                     self._child_created = True
   1297                 finally:

TypeError: expected str, bytes or os.PathLike object, not bool
python subprocess
1个回答
0
投票

根据子流程文档

args 对于所有调用都是必需的,并且应该是字符串或程序参数序列

所以一切都必须是字符串。单个字符串或字符串列表。因此,您可以执行以下操作:

scriptF = 'pythongScript.py'
arg1= 'arg1'
arg2= 'arg2'
arg3= True

subprocess.call([
    "python", scriptF, 
    "--arg1", arg1,
    "--arg2", arg2,
    "--arg3" if arg3 else ''
])

我假设在

pythongScript.py
中你有一个像这样的argparse参数

parser.add_argument('--arg3', action='store_true')

因此,如果

--arg3
不存在,那么它只是错误的

© www.soinside.com 2019 - 2024. All rights reserved.