我正在学习python并遇到了一个我无法弄清楚如何做的问题。为了简单起见,我假设我有2个脚本:Main和CalledScript。我希望Main打开一个可执行文件并获取它的pid,将其分配给一个变量然后打开CalledScript.py作为子进程并将该变量作为参数传递给它。虽然我知道在大多数情况下使用import会是一个更好的选择,在我的情况下,由于项目的其他部分,我必须将其作为子进程运行。无论如何,当我这样做时,我一直都会收到错误。它只发生在我尝试发送pid时。如果我要分配变量" thePid"下面只有一些随机数,如" 555"它会工作得很好。 CalledScript会收到它,将它打印到屏幕上,一切都很好。但是尝试将其分配给cproc.pid并发送它并不会很好。
没有进一步的延迟,这是一个简单的示例代码:
Main.py
from subprocess import Popen, PIPE
import sys
import subprocess
import os
cproc = Popen("C:\Test\Test.exe", stdin=PIPE, stdout=PIPE)
thePid = cproc.pid
theproc = subprocess.Popen(['C:\\CalledScript.py', thePid], shell=True)
CalledScript.py
import sys
print "thePid is: %r" % sys.argv[1]
我得到的错误:
Traceback (most recent call last):
File "main.py", line 12, in <module>
theproc = subprocess.Popen(['C:\\CalledScript.py
', cproc.pid], shell=True)
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 852, in _execute_child
args = list2cmdline(args)
File "C:\Python27\lib\subprocess.py", line 587, in list2cmdline
needquote = (" " in arg) or ("\t" in arg) or not arg
TypeError: argument of type 'int' is not iterable
任何帮助都会很棒!对不起,可能非常明显的问题。我在谷歌上搜索过,但没有找到答案的运气好!我前几天刚开始搞乱python,所以我还在学习!
答案 0 :(得分:2)
尝试将pid作为字符串传递,而不是作为int:
theproc = subprocess.Popen(['C:\\CalledScript.py', str(thePid)])
如果你将参数作为字符串列表传递,那么使用shell=True
是没有意义的。
答案 1 :(得分:0)
对我来说,使用这个作品:
theproc = subprocess.Popen("./CalledScript.py " + str(thePid),shell=True)
但使用它不起作用:
theproc = subprocess.Popen(['./CalledScript.py', str(thePid)], shell=True)
ubuntu,python 2.7.2 +