简体   繁体   English

Pycharm,importError no module name, when using os.system

[英]Pycharm, importError no module name, when using os.system

I'm building in Pycharm a script (let's call it script1 ) that calls another script (let's call it script2 ) that take parameters as input我正在 Pycharm 中构建一个脚本(我们称之为script1 ),该脚本调用另一个将参数作为输入的脚本(我们称之为script2

script2 is using in it xlrd ( import xlrd ) when I run script2 manually and give it the needed parameters, it works very well当我手动运行script2并为其提供所需的参数时, script2在其中使用xlrdimport xlrd ),它运行良好

script1 , calls script2 (using os.system() ) as follow: script1调用script2 (使用os.system() )如下:

os.system("python script2 -param1 ..")

and I get this error:我得到这个错误:

from file script2来自文件 script2

import xlrd导入 xlrd

ImportError: No module named 'xlrd'导入错误:没有名为“xlrd”的模块

does anyone know how to fix it?有谁知道如何修理它? or make it work correctly?或者让它正常工作?

I made sure of the parameters I give as input, they are right and xlrd is defined in project interpreter我确定了我作为输入给出的参数,它们是正确的并且 xlrd 在项目解释器中定义

Thanks a lot非常感谢

Make sure both files are in the same folder. 确保两个文件都在同一文件夹中。 Do you have more than one installation/virtualenv of python? 您是否有多个安装/ python虚拟化环境?

A better option to ruse python code is defining functions and importing them: 更好地使用python代码的方法是定义函数并导入它们:

#script2.py
import xlrd
def foo():
    print("I AM IN FOO NOW!")

#script1.py
import script2
script2.foo()

If yo are sure about calling script2 in a different process, consider using subprocess.check_output as a somewhat better API. 如果哟是肯定不同的进程调用SCRIPT2,可以考虑使用subprocess.check_output作为稍好API。

You are probably calling the wrong python. 您可能在调用错误的python。 If running python script2... from the command line works, use where python to get the full path and use it when calling os.system , for example: 如果可以python script2...运行python script2... ,请使用where python获取完整路径,并在调用os.system时使用它,例如:

os.system("c:\pythons7\python script2 -param1 ..")

(BTW - It is recommended to replace os.system with subprocess.call or some other subprocess function) (顺便说一句- 建议替换 os.systemsubprocess.call或一些其他子功能)

Something that has helped me fix this issue in the past is appending the main file path at the top of the script you are running through os.system过去帮助我解决此问题的方法是在您通过 os.system 运行的脚本顶部附加主文件路径

 import sys # for sys.path.append('/home/user/your_folder_with_python_scripts')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM