2017-04-25 130 views
-1

我很困惑。所以我想用我的程序program10.py它使用其他程序,例如other_programPython子进程命令行错误

所以我可能会像这样运行:

python3 program10.py other_program 

other_program接受一个int参数 这里是我的program10.py代码:

import time 
import subprocess 
n = 2**10 
myList = [] 
while n <= 2**15: 
    before = time.process_time() 
    subprocess.call(n) 
    after = time.process_time() 
    print(n, after-before) 
    myList.append(after-before) 
    n *= 2 

print(myList) 

当然,我得到这个大错误:

Traceback (most recent call last): 
    File "program10.py", line 7, in <module> 
    subprocess.call(n) 
    File "/usr/lib/python3.5/subprocess.py", line 557, in call 
    with Popen(*popenargs, **kwargs) as p: 
    File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ 
    restore_signals, start_new_session) 
    File "/usr/lib/python3.5/subprocess.py", line 1440, in _execute_child 
    args = list(args) 
TypeError: 'int' object is not iterable 

我毫不怀疑我使用subprocess.call是完全错误的,因为我不明白这一点,也没有其他SO问题或Python文档帮助我解决问题。如果任何人都可以告诉我它与我的程序有什么关系,那意味着很多。

+1

第一次通过循环,尝试执行'subprocess.call(2 ** 10)' 。第二次是'subprocess.call(2 ** 11)'。 Python期望的是要执行的程序的*名称*也许是'sys.argv [1]'传递给你的程序的命令行参数... – jasonharper

回答

1

您应该给出您试图在subprocess.call()中运行的程序的名称。该错误表示int不可迭代。 Iterables是字符串,列表或元组等对象。它们是“包含”多个项目的对象,并且可以一次返回一个项目。 subprocess.call()通常需要包含命令和您想要运行的任何参数的列表。例如:

subprocess.call(['other_program', str(n)])

但这只会返回程序的返回码。如果您需要程序创建的任何输出,您将需要使用不同的函数,如subprocess.check_output()

+0

谢谢!我试图找到在我的程序中运行该可执行文件所需的时间。这就是为什么我使用前后时间的原因,但似乎无论使用什么代码,无论我的整数值有多大,都需要相同的时间。它不应该这样做。数据越大,应该花费更多的时间。还有什么我做错了吗?我改变了我的subprocess语句:'subprocess.call(sys.argv [1])' – Coder117

+0

你可能不会传递'n'值给程序。试试这个: 'subprocess.call([sys.argv [1],n])' –

+0

hmmm没有任何效果。 – Coder117

1

行“TypeError:'int'对象不可迭代”告诉你该函数需要一个可迭代的,而不是一个整数。尝试传递一个字符串或一串字符串。