简体   繁体   中英

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

script2 is using in it xlrd ( import xlrd ) when I run script2 manually and give it the needed parameters, it works very well

script1 , calls script2 (using os.system() ) as follow:

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

and I get this error:

from file script2

import xlrd

ImportError: No module named '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

Thanks a lot

Make sure both files are in the same folder. Do you have more than one installation/virtualenv of python?

A better option to ruse python code is defining functions and importing them:

#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.

You are probably calling the wrong 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:

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

(BTW - It is recommended to replace os.system with subprocess.call or some other subprocess function)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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