Python 目录中的子进程和 运行 脚本

Python subprocess and running script on directory

我正在尝试 运行 子进程。我 运行 在目录上创建一个 python 文件(以转换目录中的每个文件。)转换器工作并且我一直将它实现到 gui (PYQT4) 中。这是我到目前为止得到的:

def selectFile(self):



    self.listWidget.clear() # In case there are any existing elements in the list
    directory = QtGui.QFileDialog.getExistingDirectory(self,
                                                       "Pick a folder")


    if directory:
        for file_name in os.listdir(directory):
            if file_name.endswith(".csv"):
                self.listWidget.addItem(file_name)
                print (file_name)




def convertfile(self, directory):

    subprocess.call(['python', 'Createxmlfromcsv.py', directory], shell=True)

我得到的错误是..

Traceback (most recent call last):
  File "/Users/eeamesX/PycharmProjects/Workmain/windows.py", line 162, in convertfile
    subprocess.call(['python', 'Createxmlfromcsv.py', directory], shell=True)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
TypeError: execv() arg 2 must contain only strings

感谢对初学者的任何帮助:)

在 "subprocess.call(['python', 'Createxmlfromcsv.py', directory], shell=True)" 中,'directory' 变量不是字符串。

从评论到问题,行:

    self.convertButton.clicked.connect(self.convertfile)

将在单击按钮时将 False 发送到 convertfile 方法,这就是您看到该错误的原因。

您需要向 convertfile 添加一些代码,它从列表小部件中的所选项目获取目录路径。类似于:

    item = self.listWidget.currentItem()
    if item is not None:
        directory = unicode(item.text())
        subprocess.call(['python', 'Createxmlfromcsv.py', directory])

但请注意,您没有将完整的目录路径存储在列表小部件中,因此子进程调用可能会失败。您真的应该像这样将项目添加到列表小部件中:

    self.listWidget.addItem(os.path.join(directory, file_name))